Axios不会发送cookie,Ajax(xhrFields)也不错

mic*_*ael 8 javascript ajax axios

使用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'));
    })
  }
};
Run Code Online (Sandbox Code Playgroud)

使用Axios的结果

使用Axios时的Chrome网络标签

使用$ .ajax

$.ajax({
  url: " http://local.example.com:3001/api/notification/sendAll",
  method: "post",
  data: {},
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  }
})
Run Code Online (Sandbox Code Playgroud)

结果使用$ .ajax

使用$ .ajax时的Chrome网络标签

在尝试将数据附加到POST时,我无法强制Axios发送POST(cookie不会以任何方式发送).我的服务器设置(快递):

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();
});
Run Code Online (Sandbox Code Playgroud)

我没有定义OPTIONS路线.我希望Axios使用cookie发送POST.

router.post('/notification/sendAll', function (req, res, next) {
  res.sendStatus(204);
  // ...
});
Run Code Online (Sandbox Code Playgroud)

Dan*_*515 20

我面临着类似的问题.通过Axios发出get/post请求并未发送与直接XHR请求相同的标头.

然后我刚刚在Axios require语句之后添加了以下内容:

axios.defaults.withCredentials = true;
Run Code Online (Sandbox Code Playgroud)

之后,Axios开始像常规的XHR请求一样发送我的cookie.

  • 在这里呼应。像这样设置默认值让它工作真是太疯狂了。更疯狂的是,个人请求 ``withCredentials:true`` 对其没有影响。无论哪种方式,感谢您弄清楚。 (2认同)