I am trying to call a JSON resource from a URL (on a Node.Js) environment from a React JS project. My attempts so far fail or return nothing.
The Resource API
/* GET users listing. */
app.get('/', function (req, res, next) {
// res.send('respond with a resource');
res.json([{
id: 1,
name: "Hiccup",
password: 'hiccup'
}, {
id: 2,
name: "King Arthur",
password: 'king-arthur'
}]);
});
React JS
componentDidMount() {
let url = 'http://localhost:4000/';
const myHeaders = new Headers();
fetch(url, {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
})
.then(res => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.json();
})
.then(data => {
this.setState({ revData: data })
})
.catch(err => this.setState({ revData: err }));
}
This gives an error:
Access to fetch at 'http://localhost:4000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
:4000/:1
Failed to load resource: net::ERR_FAILED
Changing mode: 'cors', to mode: 'no-cors' doesn't help.
What am I missing? How should I be going on about it?
Thank you all in advance.
express-corsmodule to avoid having to set the headers manually.