i have in my front-end side the following code:
fetch("http://localhost:3000/data", { method: "PUT" } )
.then(res => res.json())
.then(data => console.log(data))
and in my back-end side the following code:
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Content-Type', 'application/json');
if (req.url === '/data' && req.method === 'PUT') {
res.writeHead(200);
res.end(JSON.stringify({ name: 'Ahmed', age: 21, method: 'put' }));
}
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
when i run my app in the both side i have in my console the following errors:
- Access to fetch at 'http://localhost:3000/data' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
- PUT http://localhost:3000/data net::ERR_FAILED.
- Uncaught (in promise) TypeError: Failed to fetch at script.js:5:1.
the more confusing thing is when i changed the back-end code and use the express and cors the app worked properly:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: 'http://127.0.0.1:5500' }))
app.put('/data', (req, res) => {
res.json({name: 'Ahmed', age: 21, method: 'put'})
})
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
why exactly that happens, and how can i make the first back-end code work normally as the second. can anyone provide a good answer?. thank you!.