the no-cors works different to what I have expected:
Effectively, the response you get from making such a request (with no-cors specified as a mode) will contain no information about whether the request succeeded or failed , making the status code 0. Removing mode from your fetch call will show that the CORS had in fact failed.
So what is the right way to remove the CORS error when fetching from other port on same domain?
I managed to get to the same unexpected end of data error message as you, fetching using no-cors and trying to receive some echoed json data from a php file.
Albeit this works, I do feel it is a bit like a using a sticking-plaster. I admit I don’t know enough about CORS or how to configure the server to fix this properly.
Edit: or with async/await
async function fetchJSON(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.text();
return (data) ? JSON.parse(data) : {};
}
catch (error) {
console.error(error);
}
}
fetchJSON('http://localhost/json-test/somefile.php')
.then(console.log)
Yes the problem is the content type application/json. When you set this header, the cors check takes effect. This means the browser is sending a kind of „check“ request to the server and the answer must have the Access-Control-Allow-Origin set in the header.
Here is a good explanation how it should work.
Problem is that I tried to set all this headers in the servers answer but it doesn’t work.
I can show my attempts in detail tomorrow when I am back at the desk. Now I am already of work.
For Nodejs there is a middleware cors package. Just install and add to your Nodejs and your done.
Example for Nodejs express:
import cors from 'cors';
import express from 'express';
var app = express();
var corsOptions = {
origin: 'http://localhost',
optionsSuccessStatus: 200 // For legacy browser support
}
app.use(cors(corsOptions));