In addition to the no-cors
problem Quentin pointed out with the duplicate (which he answers here), there are several other issues:
What you're sending isn't JSON:
res.send('Hello world'); // <=== This is plain text
...so response.json()
would fail when trying to parse the response.
If you're just sending text like that, you'd use response.text()
to read it instead of .json()
.
You're also not checking correctly for HTTP errors. It's not just you, almost everyone makes this mistake (which I've written up here), it's a flaw (IMHO) in the fetch
API. To correctly check for errors and receive text (rather than JSON), see ***
comments:
function displayItems()
{
fetch('http://172.30.117.7:3000/users',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
},
mode:'no-cors'
})
.then((response) => {
// *** Check for HTTP failure
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
// *** Read the text of the response
return response.text();
})
.then((message) => {
// *** Use the text
alert(message);
})
.catch((error) => {
/* ...*** handle/report error, since this code doesn't return the promise chain...*/
});
}
Alternately, if you wanted, you could send back JSON:
response.json({message: "Hi there"});
...and then on the client:
function displayItems()
{
fetch('http://172.30.117.7:3000/users',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
},
mode:'no-cors'
})
.then((response) => {
// *** Check for HTTP failure
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
// *** Read and parse the JSON
return response.json();
})
.then((res) => {
// *** Use the object
alert(res.message);
})
.catch((error) => {
/* ...*** handle/report error, since this code doesn't return the promise chain...*/
});
}
But again, all of that is aside from the primary problem Quentin pointed out with the duplicate.