This code gives me an err: 'Failed to connect blocked by cors’, but im not using cors in my server.
full error message:
Access to fetch at 'http://localhost:3000/newPerevrences' from origin 'http://localhost:3001' 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.
async function changePereferences(newPereferences) {
const response = await fetch('http://localhost:3000/newPereferences', {
method: 'POST',
body: JSON.stringify(newPereferences),
headers: {
'Content-Type':'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'
}
});
const resData = await response.json();
if(!response.ok) {
throw new Error('Failed to update perevrences')
};
return resData.message;
}
This function is in a separate file but I'm calling it in my App.jsx
Server Packages:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
server.js:
const express = require('express');
const port = 3000;
const fs = require('fs');
const app = express();
app.use(express.json());
//paths
app.put('/newPereferences', async (req, res) => {
const newPerevrences = req.body.newPerevrences;
await fs.writeFile('./perevrences.json', JSON.stringify(newPerevrences));
res.status(200).json({ message: 'Perevrences updated successfully!'})
})
app.listen(port, () => {
})
I added the headers:
{'Content-Type':'application/json', 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'}
but it didn't solve my problem.
Just use
const cors = require("cors");
app.use(cors())
everything will work fine.
For more details visit https://expressjs.com/en/resources/middleware/cors.html