微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

使用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的结果

Chrome network tab when using Axios

使用$.ajax

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

结果使用$.ajax

Chrome network tab when using $.ajax

在尝试将数据附加到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();
});

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

router.post('/notification/sendAll', function (req, res, next) {
  res.sendStatus(204);
  // ...
});

解决方法:

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

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

axios.defaults.withCredentials = true;

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐