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 的结果
Result using 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屋!