uni-app请求封装

发布时间 2023-06-13 17:55:08作者: 小贺吖

  1.http.js

//你的请求地址(线上或线下)

export const BASE_URL = 'http://xxx.xxx.xx.xxx:xxxx/'; 
export const http = (options) => {
  return new Promise((resolve, reject) => {
    let token = "",tokenName='';
    let header={
      'content-type': 'application/json',
    }
    header[tokenName]=token;
    uni.request({
      url: BASE_URL + options.url, //请求地址
      method: options.method || 'GET',//请求方法
      header,
      data: options.data || {},//参数
      success: (res) => {//成功回调
        resolve(res);
      },
      fail: (err) => {//失败回调
        uni.showToast({
          icon: 'none',
          title: '请求失败!'
        })
        reject(err)
       },
      complete() {}
    })
  })
}

  2.main.js

import {http} from '@/utils/http.js';
Vue.prototype.$request = http;

  3.使用:

this.$request({
  url: 'xxx',
  data: {},
}).then(res => {//成功
  if (res.data.code == 200) {}//成功状态码判断
}).catch(err=>{});//失败