Home > Software engineering >  Cors is not working for two different origins
Cors is not working for two different origins

Time:01-23

I have two servers, frontend (Next.js) and backend (express.js api server).

Frontend server is running without any additions. But I have an nginx proxy for backend.


So far everything is good because they are not connected yet.

  • Frontend: is working as it should be.

  • Backend: I can make calls directly from the backend itself (by self origin).enter image description here

When I make a fetch get call from my frontend server to the backend server, it normally gives a cors error because the origins are different.

For this, I set the backend server with cors:

// /src/middlewares/cors.ts
import cors from 'cors';
const whitelist = new Set(['http://192.168.1.106:3000', 'https://192.168.148.132']);
// frontend: http://192.168.1.106:3000
// backend: https://192.168.148.132
const corsOptions = {
  optionsSuccessStatus: 200,
  origin: (origin: any, callback: any) => {
    console.log('origin: '   origin);
    if (whitelist.has(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  //   credentials: true,
};
export default cors(corsOptions);

and

// /app.ts
import cors from './middlewares/system/cors.js';
.
.
// setup cors
app.options('*', cors);
app.use(cors);
.
.

After doing this, I reach my main goal. The frontend server can make call to the backend server. enter image description here output: enter image description here

But this time I notice a problem. I can't send self request to backend anymore (by self origin).

enter image description here

When dealing with this I looked at the origins that came to the /src/middlewares/cors.ts file that I showed above.

enter image description here

  • for frontend: enter image description here
  • for backend: enter image description here

I am using self signed ssl in nginx for back server. And there is not any cors relevant headers in conf.

How can i solve this situation?

(If I'm missing something, you can point it out in the comments.)

CodePudding user response:

The Origin header is only set in cross-origin requests. If you call your backend directly, the Javascript value is undefined, and in this case you must not restrict anything. You could, for example, write

if (!origin || whitelist.has(origin)) {
  callback(null, true);
}
  •  Tags:  
  • Related