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

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
阅读 2.6k
2 个回答

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

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

get('/goods/', {}, { token: false }).then(res => {}).catch(err => {})
这样看看吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题