Search code examples
javascriptfetch

fetch get request is failing to get resource


when I try this url in the browser, I get a success. But when I try it with fetch, the request never gets to the server.

        let url = "http://127.0.0.1:8081/hey";

        let params = {
            method: "GET",         
        };
        fetch(url, params)
            .then((res) => {
                console.log("serverTestButton", res);
            })
            .catch(function (e) {
                console.log("error", e);
            });

Solution

  • Browsers will strict cors requests originated from fetch and XMLHttpRequest APIs. Normally, Browsers will send a preflight requests to check if the server accepts requests from a cross origin document. To enable your server to accept cors requests you need to set Access-Control-Allow-Origin: * or use a library like cors if you are using express.js. The document has a different origin in case it has a different port, url or a protocol.