Typeerror failed to fetch – How to Fix TypeError: Failed to fetch and CORS in JavaScript?

Typeerror failed to fetch: The “TypeError: Failed to fetch” error can arise for several reasons:

  • Passing an incorrect or incomplete URL to the fetch() method.
  • The server to which you are making a request does not return the correct CORS headers.
  • The URL has an incorrect protocol.
  • Passing a wrong method or headers to the fetch() method.

Let us see the examples to know how this error occurs and try to fix them.

async function getEmployDetails() {
  try {
    // Here we are passing incorrect/incomplete URL.
    // Hence TypeError: Failed to fetch occurs
    const url_response = await fetch('https://jhgdwyhnzlk.com/udybsjhdir');
    // check if the status of url response is not okay (failed)
    if (!url_response.ok) {
      throw new Error(`Error! status: ${url_response.status}`);
    }
    // if the response is okay then apply the json() function on url response
    const output = await url_response.json();
    // return the result(response) from the url
    return output;
  } catch (error) {
    // If any error occurs then in the catch block print it
    console.log(error);
  }
}
// Call the getEmployDetails() function
getEmployDetails();

Explanation:

Since the URL we passed to the fetch method was incorrect, we received two errors:

  • CORS: No ‘Access-Control-Allow-Origin’ header is present on the requested resource
  • TypeError: Failed to fetch

Fixing “TypeError: Failed to fetch” Error

Typeerror: failed to fetch: Check that the URL that you are passing to the fetch() method is complete and valid. Do the following for this:

  • Include the protocol, for example, https:// or http:// if you are testing on localhost without an SSL certificate.
  • The URL path must be correct, for example, /btechgeeks.
  • The HTTP method must be appropriate for the path specified.
  • If you misspell any of the configuration, such as a property in the headers object or an HTTP method, you will receive an error.

To resolve the "TypeError: Failed to fetch," ensure that the correct configuration is sent to the fetch method, including the URL, HTTP method, headers, and that the server to whom you are making a request is setting the necessary CORS headers with the response.

// 
async function getWebsiteDetails() {
  try {
    // Pass the url as an argument to the fetch() function
    const url_response = await fetch('https://randomuser.me/api/', {
      // Add request method
      method: 'GET',
      // Add headers of the request using the accept
      headers: {
        accept: 'application/json',
      },
    });
    // check if the status of url response is not okay (failed)
    if (!url_response.ok) {
      throw new Error(`Error! status: ${url_response.status}`);
    }
    // if the response is okay then apply the json() function on url response and store the response in a variable
    const output = await response.json();
    // return the result(response) from the url
    return output;
  } catch (error) {
    // If any error occurs then in the catch block print it
    console.log(error);
  }
}
// Call the getEmployDetails() function
getWebsiteDetails();

NOTE:

If we perform a POST, PUT, or PATCH, make sure the body is passed to the JSON.stringify()
method in the fetch method call.

If the configuration that you pass to the fetch method is correct, check to see if your server is sending the correct/valid CORS headers in the response.

Along with the response, the server must set the following CORS headers:

# Paste your domain/server link below like http://localhost:5000
Access-Control-Allow-Origin: http://example.com

Access-Control-Allow-Methods: POST, PUT, PATCH, GET, DELETE, OPTIONS

Access-Control-Allow-Headers: Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization

Depending on your use case, you may need to adjust the values, by opening the Network tab in your browser, clicking on the request, and seeing if your server is setting these CORS-related headers.

The headings are as follows:

Access-Control-Allow-Origin: It specifies which origins are permitted/allowed to make requests to the server.

Access-Control-Allow-Methods: It specifies which HTTP methods the origins are permitted to use when making requests to the server.

Access-Control-Allow-Headers: It specifies which HTTP headers origins are permitted to use when making requests to the server.