1

Solved:

Turns out content-type: false was the answer. https://stackoverflow.com/a/8244082/1694116


Question, for posterity:

For quick prototyping purposes I used Axios to POST to an API, and everything was fine and dandy. Due to client requirements, I cannot use Axios in deployment, I have to use jQuery. This is where the problem lies.

With Axios, the server sends the correct headers as a response: enter image description here

Request header: enter image description here

However, with jQuery, I do not get the Access-Control-Allow-Origin header: enter image description here

Request header: enter image description here

The payload is exactly the same, as I am making the requests at the same time (for testing).

Naturally, because the jQuery response is missing the correct header response, I get the error No 'Access-Control-Allow-Origin' header is present on the requested resource..

Code:

var formData = new FormData();
var input = this.$form.find('#image');

formData.append('image', input[0].files);
formData.append('action', 'upload_image');
formData.append('api_key', this.apiKey);

function successCb(data) {
    console.log(data);
}

// This is all that was required to get Axios to work
axios.post(apiEndpoint, formData)
    .then(successCb);

// jQuery Ajax request
$.ajax({
    type: 'POST',
    url: apiEndpoint,
    crossDomain: true,
    data: formData,
    success: successCb,
    processData: false,
    contentType: 'multipart/form-data'
});

Things to note:

If I don't set the contentType in jQuery, the request does a pre-flight request, which fails. Am I missing something with jQuery here?

If I set the dataType in jQuery to 'json', I still get the error. If I set the dataType to 'jsonp', the request doesn't even get made.

Using XMLHttpRequest() works.

Alex McCabe
  • 1,852
  • 2
  • 20
  • 33
  • I'd look at the *request* headers to see what's different, then look for the jQuery option to make it emit/not emit whatever's missing/added/different. – T.J. Crowder Sep 25 '17 at 15:56
  • @T.J.Crowder I have added screenshots of the request headers. The only difference is the `Accept` header. Explicitly forcing the `Accept` header does not make a difference. – Alex McCabe Sep 25 '17 at 16:00
  • 1
    Turns out `content-type: false` was the answer. https://stackoverflow.com/a/8244082/1694116 – Alex McCabe Sep 25 '17 at 16:31
  • Odd that that and what it links to both say that jQuery will set the content type wrong if you don't do that, but it looks right in the request headers you posted. Still, good find! – T.J. Crowder Sep 25 '17 at 16:37

0 Answers0