uni.request封装,全局配置,接口调用的封装

1.环境配置 (可参考uni-官网的环境配置)

common文件夹下新建config.js

let url_config  = ""

if(process.env.NODE_ENV === 'development'){
    // 开发环境
    url_config  = "http://192.168.0.153:8080/app/"
}else{
    // 生产环境
    url_config  = 'http://192.168.0.153:8080/app/'
}

export default url_config 

2.common文件夹下创建一个http.js

import baseUrl from './config.js'
const httpRequest = (opts, data) => {
    let httpDefaultOpts = {
        url: baseUrl+opts.url,
        data: data,
        method: opts.method,
        header: opts.method == 'get' ? {
        'X-Requested-With': 'XMLHttpRequest',
        "Accept": "application/json",
        "Content-Type": "application/json; charset=UTF-8"
    } : {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
        dataType: 'json',
    }
    let promise = new Promise(function(resolve, reject) {
        uni.request(httpDefaultOpts).then(
            (res) => {
                resolve(res[1])
            }
        ).catch(
            (response) => {
                reject(response)
            }
        )
    })
    return promise
};
//带Token请求
const httpTokenRequest = (opts, data) => {
    let token = "";
    uni.getStorage({
        key: 'token',
        success: function(ress) {
            token = ress.data
        }
    });
    //此token是登录成功后后台返回保存在storage中的
    let httpDefaultOpts = {
        url: baseUrl+opts.url,
        data: data,
        method: opts.method,
        header: opts.method == 'get' ? {
        'Token': token,
        'X-Requested-With': 'XMLHttpRequest',
        "Accept": "application/json",
        "Content-Type": "application/json; charset=UTF-8"
    } : {
        'Token': token,
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
        dataType: 'json',
    }
    let promise = new Promise(function(resolve, reject) {
        uni.request(httpDefaultOpts).then(
            (res) => {
                resolve(res[1])
            }
        ).catch(
            (response) => {
                reject(response)
            }
        )
    })
    return promise
};
 
export default {
        baseUrl,
        httpRequest,
        httpTokenRequest                    
}

3.全局配置在main.js中新增

import request from './common/http.js'
Vue.prototype.$request = request

4.接口调用 

let opts={
  url: '/api/device/add',
  method: 'post'
};
let param={
  deviceId:this.deviceCode,
  deviceName:this.deviceName
};
http.httpTokenRequest(opts, param).then(res => {
  console.log(res.data);
    //打印请求返回的数据  
},error => {console.log(error);})

你可能感兴趣的:(uni-app)