How to fix React Js TypeError: Failed to fetch

Last updated : Jul 30, 2023 12:00 AM

The most common cause for this error is CORS restrictions. If the API is hosted on a different domain or port than my React app, I may need to configure CORS headers on the server to allow my app to access it.

Here is my code that throws the error.

API requestDescription
useEffect(() => {
  fetch("http://localhost:8090/core/1/home")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error))
}, [])
Fetch errorDescription
Uncaught (promise) TypeError: Failed to fetch 
at MyReactComponent.js:6:1 
at commitHookEffectListMount (react-dom.development.js:23150:1) 
at commitPassiveMountOnFiber (react-dom.development.js:24926:1) 
at commitPassiveMountEffects_complete (react-dom.development.js:24891:1) 
at commitPassiveMountEffects_begin (react-dom.development.js:24878:1) 
at commitPassiveMountEffects (react-dom.development.js:24866:1) 
at flushPassiveEffectsImpl (react-dom.development.js:27039:1) 
at flushPassiveEffects (react-dom.development.js:26984:1) 
at react-dom.development.js:26769:1 
at workLoop (scheduler.development.js:266:1) 
(anonymous)

How to fix it?

1. Configure CORS headers on the server to allow your app to access it.

If your API is built with SpringBoot, add @CrossOrigin annotation to the controller.

SpringBootDescription
@RestController
@RequestMapping("/core/1")
@CrossOrigin(origins = "*")
public class HomeController {

    @GetMapping("/home")
    public String home() {
        return "Hello, world!";
    }
}

2. In Python, I can enable CORS by adding appropriate headers to the HTTP response returned by the API endpoints. The headers include Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Allow-Credentials.

Here's an example of how to enable CORS for all origins in a Flask API.

FlaskDescription
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/data')
def get_data():
    data = {'key': 'value'}
    response = jsonify(data)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    response.headers.add('Access-Control-Allow-Credentials', 'true')
    return response

if __name__ == '__main__':
    app.run()

3. In .NET, I can configure CORS for specific endpoints by adding the EnableCors attribute to the controller or action methods.

.NETDescription
using Microsoft.AspNetCore.Mvc;

namespace YourAppNamespace.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        [EnableCors("AllowAllOrigins")]
        public ActionResult<string> Get()
        {
            return "Hello, world!";
        }
    }
}

4. In Node.js, I can enable CORS using the CORS package or setting the appropriate headers in the Node.js application.

In this example, the CORS middleware is used to enable CORS for all routes in the application.

Node JsDescription
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/api/data', (req, res) => {
  const data = { message: 'Hello, world!' };
  res.json(data);
});
app.listen(8080, () => {
  console.log('Server listening on port 8080');
});

If I want to allow CORS only for specific domains:

For specific domainsDescription
const express = require('express');
const cors = require('cors');
const app = express();

const corsOptions = {
  origin: 'http://example.com'
};

app.use(cors(corsOptions));

app.get('/api/data', (req, res) => {
  const data = { message: 'Hello, world!' };
  res.json(data);
});
app.listen(8080, () => {
  console.log('Server listening on port 8080');
});

There are other factors that can contribute to this issue besides CORS. They are:

  1. Make sure the URL is correct and valid. Check if you can access the URL directly from the browser to confirm that it's available.
  2. Check if the server is running and accessible. Confirm that the API is currently online and accepting requests.
  3. Ensure that the fetch request is being made with the correct HTTP method. By default, fetch uses the GET method, but if the API requires a different method (such as POST, PUT, DELETE), you need to specify it in the fetch options.
  4. Verify if there is any authentication required to access the API. If the API requires authentication, make sure you are sending the necessary credentials (such as an access token) in the fetch request headers.
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...