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

时间:2016-12-02 21:30:41

标签: 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'));
    })
  }
};

使用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

我无法强制Axios在尝试将数据附加到POST时发送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);
  // ...
});

2 个答案:

答案 0 :(得分:18)

我遇到了类似的问题。通过Axios发出get / post请求并未发送与直接XHR请求相同的标头。

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

axios.defaults.withCredentials = true;

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

答案 1 :(得分:0)

使用Danielo515's回答的工作示例:

afterlayout: function(form) {
  var defaultFocusCmp = form.down('[name=first]');
  if (!defaultFocusCmp.focused) {
    defaultFocusCmp.focus();
    defaultFocusCmp.focused = true;
  }
}