Javascript Axios赢得';不要发送cookie,Ajax(xhrFields)做得很好

Javascript Axios赢得';不要发送cookie,Ajax(xhrFields)做得很好,javascript,ajax,axios,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',

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

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

使用$.ajax

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

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

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

我没有定义选项路线。我想让Axios发送带有cookie的帖子

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

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

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

axios.defaults.withCredentials = true;
此后,Axios开始像常规XHR请求一样发送我的cookie。

使用answer的工作示例:


查看此处的最后一条评论:@Dekel似乎超出了此范围,谢谢。在执行cors或非cors请求时,axios似乎以不同的方式处理凭据。在非cors上,我不必将Creditials设置为true,它会发送cookie,但在cors上,它不会发送cookie,直到我明确告诉它,AXIOS&cors让我花了大约两个小时来解决-为什么NODEJS会在每次请求时更改会话ID。现在我很高兴。在这里回响。像这样设置默认值可以让它正常工作,这太疯狂了。更疯狂的是,使用credentials:true的单个请求
对其没有影响。不管是哪种方式,谢谢您的解答。@UlysseBN您找到方法让它与选项请求一起工作了吗?@molerat为了使它与选项请求一起工作,您需要您的服务器声明允许您的选项请求包含这样的头