I believe I have cors configured correctly in my backend. The API is hosted on Heroku if that helps. Here is the server.js file:
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const bodyParser = require("body-parser");
const productsRouter = require("./products/products-router");
const ordersRouter = require("./orders/orders-router");
const emailsRouter = require("./emails/emails-router");
const corsOptions = {
origin: "*",
credentials: true,
optionSuccessStatus: 200,
};
const server = express();
server.use(express.json());
server.use(helmet());
server.use(cors(corsOptions));
server.use("/api/products", productsRouter);
server.use("/api/orders", ordersRouter);
server.use("/api/emails", emailsRouter);
server.use((err, req, res, next) => {
res.status(err.status || 500).json({
message: err.message,
});I
});
module.exports = server;
I get a cors error when my front-end tries to make HTTP requests to the backend. It reads as follows:
Access to XMLHttpRequest at 'https://nanasoapsbackend.herokuapp.com/api/products/categories' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Yes, my back and and front end are on different domains. This just happened all of a sudden, it was working fine with no cors errors for the past few months, and suddenly it stopped working. Any help would be greatly appreciated.
The problem is: You can't have origin * (allow everything) with allow credentials. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
You have to set up a white list (list of domains that are allowed)
const whitelist = ['http://www.example.com', 'http://www.otherexample.com']
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.includes(origin)) {
callback(null, true)
} else {
callback(new Error('Not allowed'))
}
}
}
Then on your client side (frontend) make sure you use withCredientals flag on your http agent (axios, superagent, fetc, etc)