Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios won't send cookie, Ajax (xhrFields) does just fine

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

Result using Axios

Chrome network tab when using Axios

Using $.ajax

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

Result using $.ajax

Chrome network tab when using $.ajax

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

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);
  // ...
});
like image 624
michael Avatar asked Dec 02 '16 21:12

michael


People also ask

How do I send cookies using Axios?

With axios, you can first create a new instance of axios while enabling cookies to be sent. From there, any requests made with this instance will automatically send cookies. const instance = axios. create({ withCredentials: true }); instance.

How do I enable cookies on Axios?

In axios, to enable passing of cookies, we use the withCredentials: true option.

What does withCredentials do in Axios?

The XMLHttpRequest. withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-origin requests.


1 Answers

I was facing a similar issue. Making a get/post request through Axios did not sent the same headers as a straight XHR request.

Then I just added the following just after the Axios require statement:

axios.defaults.withCredentials = true;

After that Axios started sending my cookie like the regular XHR request did.

like image 116
Danielo515 Avatar answered Oct 15 '22 17:10

Danielo515