Chris Coffeemilkcrazy's Chris Coffeemilkcrazy's - 2 months ago 14
Javascript Question

ajax xhr.upload.addEventListener not working for cross domain call

I'm trying to create a video uploading progress bar by jquery ajax call from my website to a backend service that is located on same domain, but different port

https://mywebsite.com/upload calling https://mywebsite.com:3000/api/video/upload

Here's my ajax script:

$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
}
}, false);

return xhr;
},
url: "https://mywebsite.com:3000/api/video/upload",
data: dataForm,
cache: false,
contentType: false,
processData: false,
crossDomain: true,
type: 'POST'
});


Calling this ajax, my POST request always turned into OPTIONS

OPTIONS https://mywebsite:3000/api/video/upload Invalid HTTP status code 404


When I remove the xhr function, the ajax script works fine. I was able to upload one video, but without progress listener.

My backend is built on node.js. Thanks ahead for any help.

Answer Source

When sending GET, POST methods cross domain, a "preflighted" requests is first send by OPTIONS method.

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control#Preflighted_requests

It looks like you are getting 404 Not Found response. Make sure your request target URI return something such as 200 OK, by allowing OPTIONS method requests to be sent.