Solve - TypeError - Failed to fetch and CORS in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20213 min read

banner

Photo by Lane Jackman

Solve - TypeError - Failed to fetch and CORS #

The "TypeError: Failed to fetch" occurs for multiple reasons:

  1. An incorrect or incomplete URL has been passed to the fetch() method.
  2. The server you are making a request to does not send back the correct CORS headers.
  3. A wrong protocol is specified in the url.
  4. A wrong method or headers have been passed to the fetch() method.

typeerror failed to fetch

Here's an example of how the error occurs.

index.js
async function getUser() { try { // ⛔️ TypeError: Failed to fetch // 👇️ incorrect or incomplete URL const response = await fetch('https://example.com/does-not-exist'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } getUser();

The url we passed to the fetch() method is incorrect, so we got back two errors:

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

Make sure that the URL you're passing to the fetch method is correct and complete. You have to:

  • include the protocol, e.g. https:// or http:// if you're testing on localhost without an SSL certificate
  • the path has to be correct e.g. /articles
  • the HTTP method has to be correct for the specific path
  • if you misspell any of the configuration, e.g. a property in the headers object or the HTTP method, you would get the error back.

To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method, headers and verify that the server you're making a request to is setting the correct CORS headers with the response.

index.js
// ✅ Works async function getUser() { try { const response = await fetch('https://randomuser.me/api/', { method: 'GET', headers: { accept: 'application/json', }, }); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } getUser();
If you're making a POST, PUT or PATCH, make sure that the body is passed to the JSON.stringify() method in the call to the fetch method.

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

The server should be setting the following CORS headers along with the response:

cors
# 👇️ your domain below, e.g. http://localhost:3000 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

You might have to tweak the values depending on your use case, but open the Network tab in your browser, click on the request and check if your server is setting these CORS-related headers.

The headers are:

  • Access-Control-Allow-Origin - which origins are allowed to make requests to the server.
  • Access-Control-Allow-Methods - which HTTP methods the origins are allowed to use when making requests to the server
  • Access-Control-Allow-Headers - which HTTP headers the origins are allowed to use when making requests to the server

If you can't get the CORS options working, try using the * (asterisk) symbol as the origin and see if that works.

When an asterisk * is set for the Access-Control-Allow-Origin header, any origin on the internet can access the server.

You would want to narrow this down in production, but it's a useful tool when debugging.

Use the search field on my Home Page to filter through my more than 1,000 articles.