Reputation: 287
I have a Node/Express server that interacts with a React app.
I need to make POST and GET requests, the problem is that when making POST requests I get a CORS error, the usual:
Access to fetch at 'http://localhost:9000/testAPI' 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.
I specified on the response on the server the Access-Control-Allow-Origin
header, but I am not sure if I have to set this header for a POST request as well. And if I do, what domain should it specify?
I am also not willing to use hacks like CORS extensions, or npm packages. I want to use CORS.
The server-side looks like so:
const express = require("express");
const router = express.Router();
router.get("/", (req, res, next) => {
console.log(req.url);
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
res.send("API is working properly");
});
module.exports = router;
In the React app, the GET request looks like so (works just fine):
const res = await fetch('http://localhost:9000/testAPI');
console.log(res);
The POST request looks like so (CORS error thrown):
const res = await fetch('http://localhost:9000/testAPI', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ someData: "POST requests are working properly" })
});
Do I need to specify some additional headers or properties on the POST request? Or do I have to modify something on the server-side?
If I will not have this problem when going live, than I do not mind using a hack like CORS extension.
Upvotes: 0
Views: 2093
Reputation: 29
You may use this package cors
// Install
npm install cors
yarn add cors
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
// global middleware
app.use(cors());
// You can use route based middleware too
router.post("/", cors(), (req, res, next) => {
// process request & send response to client
});
Upvotes: 2