Search code examples
ajaxfirefoxcorsxmlhttprequestpreflight

CORS preflight requests working with jQuery AJAX, but failing with native XmlHttpRequests in Firefox


This question is based on an issue I had before but never managed to resolve.

I'm running an userscript via FireMonkey which regulary sends requests to my backend server, those using CORS since they are cross-domain. For testing purposes my response headers are currently set very loosely backend-side:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Method: POST");
header("Access-Control-Allow-Headers: *");

Frontend-side my requests are sent via jQuery AJAX, looking roughly like this:

$.ajax({
    method: "POST",
    url: this.queryURL,
    timeout: this.timeout,
    data: this.formData,
    processData: false,
    contentType: false,
    success: onSuccess,
    error: onError
});

Nothing special here, requests have been working fine ever since.

I want to get rid of jQuery now and use native XmlHttpRequest instead. The implementation looks like this:

const xhr = new XMLHttpRequest();
xhr.open("POST", this.queryURL);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.timeout = this.timeout;
xhr.ontimeout = onTimeout;
xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4 || xhr.status === 0)
        return;

    if (xhr.status !== 200)
        onError(xhr);
    else
        onSuccess(xhr.responseText);
};
xhr.send(this.formData);

For some reason the requests seem not to be sent anymore on Firefox, at least the network tab doesn't show any. Testing it on Chrome it still works, but I figured that the issue might have something to do with preflight requests, since I noticed something strange:

With jQuery AJAX:

With jQuery AJAX

With native XHR:

With native XHR

Using native XHR, Chrome seems to always have a first preflight request failing, with a second one being successful. This doesn't happen with AJAX. Not sure if this is helpful in any way, but could this explain why requests keep failing at all in Firefox, and how to resolve it?


Solution

  • After some more research I finally found out that this is actually a firefox-related issue with userscripts: https://bugzilla.mozilla.org/show_bug.cgi?id=1715249