const url = {
web_url: 'http://127.0.0.1:8000',
}
import $store from '@/store/index.js'
export default {
// 设置公共参数
common: {
method: 'GET',
// 请求头
header: {
'content-type': 'application/json'
},
// 请求数据
data: {}
},
// 设置通用请求
request(options = {}) {
// 请求地址
options.url = `${url.web_url}${options.url}`
// 默认请求方法
options.method = options.method || this.common.method
// 设置请求头
options.header = options.header || this.common.header
// 使用tong请求
if(options.token){
options.header.authorization = `Bearer ${$store.state.userToken}`
if(!options.header.authorization){
return uni.showToast({
title: '您还未登录,请先登录',
icon: 'none'
})
}
}
// 设置请求
return new Promise((resolve, reject) => {
return uni.request({
...options,
// 请求成功
success: (res) => {
// 请求成功返回数据
return resolve(res)
},
fail: (err) => {
uni.showToast({
title:'请求失败',
icon:'none'
})
// 停止下拉刷新
uni.stopPullDownRefresh()
return reject(err)
}
})
})
},
// 封装get 请求
get(url, data = {}, options = {}) {
options.url = url
options.data = data
options.method = 'GET'
return this.request(options)
},
// 封装post请求
post(url, data = {}, options = {}) {
options.url = url
options.data = data
options.method = 'POST'
return this.request(options)
}
}
使用GET请求例如:
get('/user/', {}, {token: true}).then(res => {}).catch(err => {})
只要有一个get请求参数为:token:true, 后面的所有请求都会自动带上authorization和令牌访问,这是怎么回事?
即使传参不带token,请求链接上也会带上authorization和令牌访问,这是哪里出问题了吗?
get('/goods/').then(res => {}).catch(err => {})
所以是第一个打印的是 undefined,之后打印的都是有值的吗?你得确定一下。然后看下是是否是调用请求的时候,定义的 options 有问题,是一个公共变量了,而不是函数内变量。得确定一下变量的作用域。你现在的代码里面并没有展示上下文内容。