reactjsaxiosxmlhttprequestfetch-apidjango-channels

Why does Axios.get(URL) not return consistently?


I am having trouble understanding why an axios.get(...url...) request does not always return a result to the frontend.

The code that does not work consistently (returns a result every other request on average) is as follows:

async function subscribeToAnalysis (analysisId) {

    await axios.get(/localhost:8000/someEndpoint/), {
        timeout: 50000,
    })
    .then(async response => {
        console.log("Response", response);
        // Do more stuff with response and recall the function to subscribe again
    };
}

However, if I swap out the axios.get(...) for a fetch(...) request, it works as expected and a result is returned every time as expected.

async function subscribeToAnalysis (analysisId) {

    await fetch(/localhost:8000/someEndpoint/))
    .then(async response => {
        console.log("Response", response);
        // Do more stuff with response and recall the function to subscribe again
    };
}

The axios.get(...) requests work fine in the backend when sending back Django Rest Response objects or HttpResponse objects. In my use-case, I am using Django Channels, so I have to explicitly send headers and then the content.

For example, I send headers via:

await self.send_headers(headers=[
            (b"Content-type", b"application/json"),
            (b"Access-Control-Allow-Origin", b"*"),
            (b"Allow", b"GET"),
            (b"Access-Control-Allow-Credentials", b"true"),
            (b"Cross-Origin-Opener-Policy", b"same-origin"),
            (b"Referrer-Policy", b"same-origin"),
            (b"Access-Control-Allow-Headers", b"Origin, X-Requested-With, Content-Type, Content-Length, Accept, Authorization"),])             

Then later, send the content for the subscribing request via:

await self.send_body(bytes(json.dumps(analysisData), 'utf-8'))

This same code works fine with the fetch() requests but not with the axios.get() requests and I am not sure why.


Solution

  • TL;DR; GET requests send an OPTIONS method request prior to the GET to get information.

    Since this question, I have instead gone an alternative route of using fetch versus Axios for requests. While debugging another issue with the task, we stumbled across that the fetch request was actually sending an OPTIONS method request prior to the GET request got sent.

    Looking up if this may happen with Axios, as well, it seems that it does (and has since been confirmed via testing). See AXIOS request method changes to 'OPTIONS' instead of 'GET' for more information.