[axios]更改 axios 实例的默认标头?

2024-05-15 755 views
1

我在标头中使用令牌进行身份验证。所以我首先创建一个axios实例来登录。登录后的所有请求都应在标头字段中携带令牌。

Q1:我应该使用instance.interceptors.request.use()注入令牌吗?

在我的集成测试中,我以不同的用户身份登录。将instance.interceptors.request.use()令牌配置累积在内部数组中,并且登录结果并不总是正确的。所以我必须instance.interceptors.request.eject()在每个之前instance.interceptors.request.use()清除内部数组。

Q2:是否有更好的方法来更改实例的默认标头?

回答

2

如果您始终知道标头的值:

axios.defaults.headers.common['Auth-Token'] = 'foo bar';

这会自动将标头添加到每个请求中。

9

@mzabriskie 感谢您的快速回复。有用。仅举例(axios v0.8.1),我设置:

instance.defaultConfig.headers.authorization = 'foo bar'
3

啊,对了。很高兴它起作用了!

3

您好,我设置后遇到问题axios.defaults.headers.common[]。在我尝试在 中设置用户令牌之前request header,请求一切正常,但它们发送OPTIONS到我的后端 和404,无论我在那里使用什么POST或方法。GET来自 chrome devTools 的图片: 开发后

我设置标题的方式是:

import axios from 'axios';

export default function setAuthorizationToken(token) {
    if(token) {
        axios.defaults.headers.common['authorization'] = `Bearer ${token}`;
    } else {
        delete axios.defaults.headers.common['authorization'];
    }
}

我知道是关于的CORS,所以我也在服务器端进行了设置:

//app.js
app.use((ctx, next) =>{

    // Website you wish to allow to connect
    ctx.set('Access-Control-Allow-Origin': '*');

    // Request methods you wish to allow
    ctx.res.setHeader();

    // Request headers you wish to allow
    ctx.res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,authorization');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    ctx.res.setHeader('Access-Control-Allow-Credentials', true);
    ctx.res.setHeader('withCredentials', true);

    // Pass to next layer of middleware
    next();
});
...

我们可以从OPTIONSdevTool 图片上的第一个请求中看到这些请求功能。


更新

解决了,问题是从第一个OPTIONS请求开始,服务器回复浏览器a 404,所以我在服务器中更改:

//app.js
app.use((ctx, next) =>{

    // Website you wish to allow to connect
    ctx.set({
                 'Access-Control-Allow-Origin': '*',
                 // Request methods you wish to allow
                 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
                 // Request headers you wish to allow
                 'Access-Control-Allow-Headers': 'X-Requested-With,content-type,authorization',
                 'Access-Control-Allow-Credentials': true,
             });

   if(ctx.req.method = 'OPTIONS') {
        ctx.res.statusCode = 204;

   }
    // Pass to next layer of middleware
    await next();
});

Then the program works.

谢谢。

6

非常感谢。 :)?

0

我认为应该改变:

if(ctx.req.method = 'OPTIONS') {
        ctx.res.statusCode = 204;
        ctx.res.end()
} else {
       next()
}
0

但似乎instance.defaults.headers.common[HEADER_NAME] = 'some value'不仅改变了实例的默认值,而且改变了任何 axios 请求的默认值,甚至直接使用axios.get()(not instance.get())

0

我也有@berdyshev 描述的相同问题。如果我需要通过创建新的 axiosInstance 来发出新的 axios 请求,并且这个新请求我需要删除一些默认标头。假设我需要删除默认的授权标头。

我期望这样的事情: delete axiosInstance.defaults.headers.common.Authorization 为了安全,因为它应该只从我创建的 axiosInstance 中删除。

不过,我还可以确认,这似乎也从主axios实例中删除了标头。

有人知道解决这个问题的方法吗?

7

我也有@berdyshev 描述的相同问题。如果我需要通过创建新的 axiosInstance 来发出新的 axios 请求,并且这个新请求我需要删除一些默认标头。假设我需要删除默认的授权标头。

我期望这样的事情: delete axiosInstance.defaults.headers.common.Authorization 为了安全,因为它应该只从我创建的 axiosInstance 中删除。

不过,我还可以确认,这似乎也从主axios实例中删除了标头。

有人知道解决这个问题的方法吗?

我有同样的问题(在0.16.2中)

1

https://github.com/axios/axios/issues/209#issuecomment-174206234

这不会更新已创建的axios v0.18“实例”

例如,您还需要执行以下操作:

const axiosInstance = axios.create({
          baseURL: 'http://example.com',
          headers: {
            'Auth-Token': 'bar foo',
          }
        });

// only affects the global instance and instances created afterwards
axios.defaults.headers.common['Auth-Token'] = 'foo bar'; 

// immediately affects this instance
axiosInstance.defaults.headers['Auth-Token'] = 'foo bar'; 
8

对我来说这很奇怪。

我创建并实例化const axiosInstance = axios.create(),更新它的标题 axiosInstance.defaults.headers.common['CUSTOM'] = 'blahblah'

之后我做了两个控制台日志:

console.table(axios.defaults.headers.common)
console.table(axiosInstance.defaults.headers.common)

你猜怎么着?他们都有CUSTOM标题?

0

伙计们,有人能帮助我吗?我想我做错了。在使用 AxiosInstance 执行新的 http 请求之前,我尝试相应地更改标头,但有时请求是在标头更改之前发送的。我需要在这里添加承诺吗?

这是一个例子:

** USERSERVICES.JS **

getUserByToken: function(token) {
        var headers = [
            { key: 'Authorization', value: 'Bearer ' + token},
            { key: 'Content-Type', value: 'application/x-www-form-urlencoded'}
        ];

        setHeaders('get', headers);
        return AxiosInstance.get('/user');
    },

这是我的 setHeaders 函数:

** SERVICECONFIG.JS **

export const setHeaders = (type, props) => {
    AxiosInstance.interceptors.request.use(config => {
        config.headers[type] = {};

        props.forEach((prop) => {
            config.headers[type][prop.key] = prop.value;
        });
        return config;
    });
}

我注意到它是相当异步的......我的实现好吗?看来我必须改变它,prolly 与承诺?