微信小程序封装wx.request请求以及携带token

       首先在pages中新建一个api的文件夹,对ajax请求统一管理,文件夹中request.js完成对wx.request的封装,在index.js中完成接口管理,目录以下图:ajax

微信小程序封装wx.request请求以及携带token_第1张图片

    在request.js中对wx.request进行封装,代码以下:json

var tokenKey = "access-token";
var serverUrl =  "http://124.204.51.174:8080/gcs"; 
// 例外不用token的地址
var exceptionAddrArr = [  '/user/login',];

//请求头处理函数
function CreateHeader(url, type) {
  let header = {}
  if (type == 'POST_PARAMS'){
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }else{
    header = {
      'content-type': 'application/json'
    }
  }
  if (exceptionAddrArr.indexOf(url) == -1) {  //排除请求的地址不须要token的地址
    let token = wx.getStorageSync(tokenKey);
    // header.Authorization = token;
    header['access-token'] = token;
  }
  return header;
}
//post请求,数据在body中
function postRequest(url,data){
  let header = CreateHeader(url,'POST');
  console.log(header,'header')
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}
//post请求,数据按照query方式传给后端
function postParamsRequest(url, data) {
  let header = CreateHeader(url,'POST_PARAMS');
    let useurl = url;
    console.log(useurl);
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + useurl,
      data: data,
      header: header ,
      method: 'POST',
      success: (res => {
        console.log(res, '1212')
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}
//get 请求
function getRequest(url, data) {
  let header = CreateHeader(url, 'GET');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'GET',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}
//put请求
function putRequest(url, data) {
  let header = CreateHeader(url, 'PUT');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'PUT',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}
//delete请求
function deleteRequest(url, data) {
  let header = CreateHeader(url, 'DELETE');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'DELETE',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => { 
         reject(res) 
      })
    })
  })
}
module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;
module.exports.postParamsRequest = postParamsRequest;
module.exports.putRequest = putRequest;
module.exports.deleteRequest = deleteRequest;

 在index.js中具体使用小程序

import { postRequest, postParamsRequest} from './requst.js'
const base = '';
// 登陆接口
export const requst_post_login = data => postParamsRequest(`/user/login`, data);
//扫码接口
export const requst_post_addInfo = data => postRequest(`/receive/add`, data);

在页面中使用,如登陆页面的login.js后端

import { requst_post_login} from '../api/index.js'
formSubmit(e){
    if (!e.detail.value.loginName || !e.detail.value.password){ 
     wx.showToast({
        title: '请输入用户名或密码',
        icon: 'none',
      })
      setTimeout(function () {
       wx.hideToast()
      }, 2000)
      return
    }
    requst_post_login(e.detail.value).then(res=>{
      res = res.data;
      if(res.code == 1){
        wx.setStorage({
          key: 'access-token',
          data: res.data.token,
        })
        wx.showToast({
          title: '登陆成功',
          icon: 'success',
        })
        setTimeout(function () {
          wx.hideToast()
        }, 2000)
        wx.navigateTo({
          url: '../home/home'
        })
      }
    }).catch(err=>{
      console.log('ajax_err',err)
    })
},

 然后再其他页面进行引用

你可能感兴趣的:(微信小程序,javascript,前端)