Axios不会发送cookie,Ajax(xhrFields)也不错 [英] Axios won't send cookie, Ajax (xhrFields) does just fine
问题描述
使用Axios
export function sendAll() {
return (dispatch) => {
dispatch(requestData());
return axios({
method: 'POST',
url: `${C.API_SERVER.BASEURL}/notification/sendAll`,
data: {prop: 'val'},
// responseType: 'json',
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}).then((response) => {
dispatch(receiveData(response));
}).catch((response) => {
dispatch(receiveError(response));
// dispatch(pushState(null, '/error'));
})
}
};
使用Axios的结果
时的标签
使用$ .ajax
$.ajax({
url: " http://local.example.com:3001/api/notification/sendAll",
method: "post",
data: {},
crossDomain: true,
xhrFields: {
withCredentials: true
}
})
结果使用$ .ajax
Result using $.ajax
在尝试将数据附加到POST时,我无法强制Axios发送POST(cookie不会以任何方式发送)。
我的服务器设置(快递):
I am unable to force Axios to send a POST when trying to attach data to POST (cookie doesnt get sent either way). My server setup (express):
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", `${C.PROTOCOL}://${C.DOMAIN}:${C.PORT}`);
res.header("Access-Control-Request-Headers", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
我没有定义OPTIONS路线。我希望Axios发送带有cookie的POST。
I do not have a OPTIONS route defined. I want Axios to send POST with cookie.
router.post('/notification/sendAll', function (req, res, next) {
res.sendStatus(204);
// ...
});
推荐答案
我遇到了类似的问题。通过Axios发出get / post请求并没有发送与XHR直接请求相同的标头。
I was facing a similar issue. Making a get/post request through Axios did not sent the same headers as a straight XHR request.
然后我刚刚在Axios require语句之后添加了以下内容:
Then I just added the following just after the Axios require statement:
axios.defaults.withCredentials = true;
之后Axios开始像常规XHR请求那样发送我的cookie。
After that Axios started sending my cookie like the regular XHR request did.
这篇关于Axios不会发送cookie,Ajax(xhrFields)也不错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!