jQuery ajax working but axios giving CORS error

Viewed 740

I am moving my project from jQuery to axios. It is working fine in other places but I am getting error in one specific place. axios is giving CORS error but jquery working fine. Here is the code:

jQuery

$.ajax({
    url: 'my-url-here',
    type: 'post',
    data: JSON.stringify({
      "attachmentNames": [ "filename.pdf" ]
    }),
    success: function (data) {
        console.info(data);
    }
});

axios

axios({
    url: 'my-url-here',
    method: 'post',
    data: {
      "attachmentNames": [ "filename.pdf" ]
    }
  }).then(function(resp) {
    console.log(resp);
  });
1 Answers

Browsers will send a preflight request if you send a Content-Type with a value that isn't on a very short list.

application/json will trigger a preflight.

Axios will, by default, encode data as JSON and say it is sending JSON.

In your jQuery, you are manually encoding the data as JSON and failing to set the correct Content-Type header. As a result you are lying to the server and claiming the data is application/x-www-form-urlencoded (the default for jQuery). This header doesn't need a preflight request.


Configure the server to respond to a preflight request with permission (in Access-Control-Allow-Headers) to change the Content-Type.

Related