您好,我设置后遇到问题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();
});
...
我们可以从OPTIONS
devTool 图片上的第一个请求中看到这些请求功能。
更新
解决了,问题是从第一个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.
谢谢。