uniapp封装request网络请求

843 阅读1分钟

1、先在根目录下创建一个http.js

const commonUrl = "此处为访问后端接口"; //公共路径

// post请求封装
function postRequest(url, data) {
    var promise = new Promise((resolve, reject) => {
        var that = this;
        var postData = data;
        uni.request({
            url: commonUrl + url,
            data: postData,
            method: "POST",
            header: {
                "content-type": "application/x-www-form-urlencoded",
                token: uni.getStorageSync("token")
            },
            success: function(res) {
                //返回什么就相应的做调整
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else {
                    // 请求服务器成功,但是由于服务器没有数据返回,此时无code。会导致这个空数据
                    //接口后面的then执行
                    // 不下去,导致报错,所以还是要resolve下,这样起码有个返回值,
                    //不会被阻断在那里执行不下去!
                    resolve(res.data.msg);
                }
            },
            error: function(e) {
                reject("网络出错");
            }
        });
    });
    return promise;
}

// get请求封装
function getRequest(url, data) {
    var promise = new Promise((resolve, reject) => {
        var that = this;
        var postData = data;
        uni.request({
            url: commonUrl + url,
            data: postData,
            method: "GET",
            dataType: "json",
            header: {
                "content-type": "application/json"
            },
            success: function(res) {
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else {
                    resolve(res.data);
                }
            },
            error: function(e) {
                reject("网络出错");
            }
        });
    });
    return promise;
}

module.exports = {
    post: postRequest,
    get: getRequest
    // imgUrl: commonImgUrl
};

2、在main.js进行全局挂载

import Vue from 'vue'
import store from './store'
import App from './App'
import myRequest from './util/http.js'

// 全局登陆状态缓存
Vue.prototype.$store = store
Vue.prototype.$myRequest = myRequest

Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

3、引用案例

async fy() {
  let data = {
    pageCount: 10
  }
  const res = await this.$myRequest.get('/Purchase/app/getHCProduct', data);
  this.goodsList = res.HCProductList;
},