0
点赞
收藏
分享

微信扫一扫

axios——有些接口需要传递token,有些接口不需要传递token的处理方法

读思意行 2022-03-12 阅读 45

今天在写后台管理系统时,遇到一个问题:
在这里插入图片描述
请求接口时,接口先是报500服务器错误,然后又报跨域问题。

问过后端,后端说请求时不要加token

由于我的其他接口都是要求带有token的,因此需要对axios拦截器单独进行处理。

下面对antd框架中的部分内容修改如下:

1.request.js文件——添加一个新的axios请求

const instancePermission = axios.create({
    timeout: 20000,
    baseURL: BASE_URL,
    withCredentials: false,
    xsrfHeaderName: xsrfHeaderName,
    xsrfCookieName: xsrfHeaderName,
    headers: {
        "accept-language": "zh-Hans"
    }
})

2.requestPermission——设置请求部分

async function requestPermission(url, method, params, config) {
    switch (method) {
        case METHOD.GET:
            return instancePermission.get(url, { params, ...config })
        case METHOD.POST:
            return instancePermission.post(url, params, config)
                // request('/api/create', 'POST', body, { params: { name: 'abc' } }) 拼接参数
        case METHOD.PUT:
            return instancePermission.put(url, params, config)
        case METHOD.DELETE:
            return instancePermission.delete(url, { params, ...config })
        default:
            return instancePermission.get(url, { params, ...config })
    }
}

3.loadInterceptors——设置拦截器部分

3.1 设置请求拦截器部分

instancePermission.interceptors.request.use(
    config => onFulfilled(config, options, true),
    error => onRejected(error, options)
)

3.2 设置响应拦截器部分

instancePermission.interceptors.response.use(
    response => onFulfilled(response, options),
    error => onRejected(error, options)
)

4.导出requestPermission

export{requestPermission}

5.在axios-interceptors.js文件中做如下处理

onFulfilled(config, options,flag) {
    var params = {...config };
    const { message } = options
    const { url, xsrfCookieName, headers } = params;
    if (!flag&&headers.Authorization && xsrfCookieName && !Cookie.get(xsrfCookieName)) {
        message.warning('认证 token 已过期,请重新登录')
    }
    if (!flag && headers.Authorization && xsrfCookieName && !Cookie.get(xsrfCookieName)) {
         message.warning('认证 token 已过期,请重新登录')
    }
    if (!flag) {
         params.headers['Authorization'] = Cookie.get(xsrfHeaderName)
    }
    return params
},

完成!!!

注意:要重新运行代码,有时候还需要清理一下缓存才能看到实际的效果。

举报

相关推荐

0 条评论