uniapp封装的request方法,GET请求一直携带token?

作者站长头像
站长
· 阅读数 23
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 showToast('请先登陆')
            }
        }


        // 设置请求
        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请求例如:

this.$http.get('/user/', {}, {token: true}).then(res => {}).catch(err => {})

只要有一个get请求参数为:token:true, 后面的所有请求都会自动带上authorization和令牌访问,这是怎么回事?

即使传参不带token,请求链接上也会带上authorization和令牌访问,这是哪里出问题了吗?

this.$http.get('/goods/').then(res => {}).catch(err => {})

我是这样使用的:

import $http from '@/utils/request.js'
// 注册全局请求方式
Vue.prototype.$http = $http
回复
1个回答
avatar
test
2024-07-02

看起来是因为封装请求的 optoins 局部状态意外共享导致的,出现这个情况的原因多半是由于挂载到 Vue 实例时错误处理导致的。

其实直接用 luch-request 就好了, uViewUI 内置的 HTTP 请求库也是这个,一些拦截器和中间件都是已经帮你封装好了。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容