一、新建名为request.js的文件
放在utils文件夹下
二、在request.js里面写入promise
const BASE_URL = `http://localhost:9090`
export const request = (options) => {
return new Promise((resolve,reject) => {
uni.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
header: {token: uni.getStorageSync('user') ? uni.getStorageSync('user').token : ''}, //在header里加上token,便于每次请求都带上token
data: options.data || {},
success: (res) => {
const data = res.data
if(data.code === '401') //权限不足
{
uni.navigateTo({
url:'/pages/login/login' //跳转至登录页面重新登录
})
return
}
else if(data.code !== '200')
{
uni.showToast({
icon:"error",
title:'操作错误'
})
return
}
resolve(data)
},
fail: (error) => {
uni.showToast({
icon:"error",
title:"系统错误"
})
reject(error)
}
})
})
}
三、在main.js里配置
挂载到vue.prototype原型链上
import { request } from './utils/request.js'
Vue.prototype.request = request
四、在页面内直接this.request使用
代码如下:
//请求
this.request({url:'/user/register',method:'POST',data:this.form}).then(res=>{
if(res.code === '200')
{
//这里进行跳转、信息缓存操作
}
})