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:
However, with jQuery, I do not get the Access-Control-Allow-Origin
header:
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.