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.
useEffect(() => {
fetch("http://localhost:8090/core/1/home")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
}, [])
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)
1. Configure
If your API is built with SpringBoot, add
@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
Here's an example of how to enable CORS for all origins in a Flask API.
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
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
In this example, the CORS middleware is used to enable CORS for all routes in the application.
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:
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: