A few days ago, my boss asked me to write a small function of scanning code to receive goods. Since the function is simple, there is no need to develop app alone, so I asked him to make a small program of wechat to realize this function. In the process of interaction between the front and back end, token should be carried on the back end. Therefore, according to the convention of vUE project, the commonly used GET, POST, PUT and DELETE of Wx. Request in wechat are encapsulated as follows.

First, create an API folder in Pages to manage Ajax requests in a unified manner. Request.js in the folder completes the encapsulation of Wx. request and interface management in index.js. The directory is as follows:



Wx. request is wrapped in request.js as follows:

var tokenKey = "access-token";
var serverUrl =  "http://124.204.51.174:8080/gcs"; Var exceptionAddrArr = ['/user/login',]; // Request header handlerfunction 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) {// Exclude the requested address does not require the token addresslet token = wx.getStorageSync(tokenKey);
    // header.Authorization = token;
    header['access-token'] = token;
  }
  returnheader; } // Post request, data in bodyfunction 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)})})})} // The data is sent to the back end in query modefunction 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 requestfunction 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 requestfunction 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 requestfunction 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;Copy the code

It is used specifically in index.js

import { getRequest, postRequest, postParamsRequest, putRequest, deleteRequest,
       } from './requst.js'const base = ' '; // Login interfaceexportconst requst_post_login = data => postParamsRequest(`/user/login`, data); // Scan interfaceexport const requst_post_addInfo = data => postRequest(`/receive/add`, data);Copy the code

Used in pages, such as login.js of the login page

import { requst_post_login} from '.. /api/index.js'
formSubmit(e){
    if(! e.detail.value.loginName || ! e.detail.value.password){ wx.showToast({ title:'Please enter user name or password',
        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: 'Login successful',
          icon: 'success',})setTimeout(function () {
          wx.hideToast()
        }, 2000)
        wx.navigateTo({
          url: '.. /home/home'
        })
      }
    }).catch(err=>{
      console.log('ajax_err',err)
    })
},
Copy the code

————————————————————————————————-

If you have any questions, welcome to discuss, if you are satisfied, please manually click “like”, thank you! 🙏

For more postures, please pay attention!!