CORS Err - Same origin is undefined in browser

24 Views Asked by At

This is node expressjs code and it is configured to allow dynamic origin.

const whitelist = ["http://localhost:8080"];
const corsOptions = {
  origin: function (origin, callback) {
    console.log(origin);
    if (whitelist.indexOf(origin) !== -1) {
      console.log(whitelist.indexOf(origin) !== -1);
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  },
  credentials: true,
};

const PORT = 5000;
const app = express();
app.use(cors(corsOptions));

a simple endpoint

app.get("/", (req, res) => {
  res.send("ok");
});

with this when i make a request from this http://localhost:8080(react app) to http://localhost:5000(backend app) is working fine and able to see response text

But when i load the app in browser (http://localhost:5000) it should show the response i.e the response text "ok". But I am getting the CORS err even it is the same origin.

But when i replace the line

app.use(cors(corsOptions));

with

app.use(cors());

I was able to see the response text in the browser when the app (http://localhost:5000) is loaded. Why is this behavior when dynamic origin is set (setting cors config). And when i try to log the origin it is showing undefined too.

const corsOptions = {
  origin: function (origin, callback) {
    console.log(origin);
    ..........

Irrespective of dynamic origin is set or not set when the app loaded in browser it should load the response text text right ? why it is not.

Another option is to add !origin to fix the issue which i am not clear correct or not.

if (whitelist.indexOf(origin) !== -1 || !origin) {....} 
0

There are 0 best solutions below