I have a FE made with react and a BE with node/express/mongodb/mongoose. This is my first attempt at trying to connect everything together. As far as I am aware everything is correct but I am still getting a CORS error but I have no idea why.
this is from my app.js in my back end
const app = express();
app.use(bodyParser.json());
app.use((res, req, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader('Access-Control-Allow-Methods','GET, POST, PATCH, DELETE');
next();
});
Instead of the wildcard I tried specifically to add 'http://localhost:3000' but that still does not work as I get the CORS error. I am pretty new to the back end so I could easily be doing something wrong here.
Any help would be greatly appreciated
EDIT: For anyone who finds this from google. The below answers did work great (installing cors package) but I also figured the issue out which works without the package. The main issue was if you see my middleware function states (res, req, next)
, I accidentally but the response first before the request which was causing these issues. So it should be (req, res, next)
I did not know this would even cause an issue so it was interesting to figure out. Hope this helps anyone in the future. One thing that did help was the cors package actually gave me some information on why it wasn't working which helped me figure it out. The error that I was receiving was because res.setHeader wasn't a function, and for some reason this is true if the response is before the request in the middleware function
CodePudding user response:
There're 2 things you can do:
- Set proxy in react package.json. For example: { "proxy": "http://localhost:3000" }
- Or you can use cors in the backend: https://www.npmjs.com/package/cors
CodePudding user response:
Try adding cors to your app.
const app = express();
const cors = require("cors"); //Add this
app.use(bodyParser.json());
app.use((res, req, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
res.setHeader('Access-Control-Allow-Methods','GET, POST, PATCH, DELETE');
next();
});
app.use(cors()); //And add this line as well