Search code examples
reactjscorsnestjs

nestJs cors origin response always return wildcard ' * '


i'm facing CORS issue between react (http://localhost:3000) and nestJs (http://localhost:4000) I added the credentials: true to both front and back as i'm going to work with secured cookies.

Here the backend nestJs side:

origin: (origin: any, callback: any) => {
  if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
    callback(null, true);
  } else {
    callback(new Error('Not allowed by CORS'));
  }
},
credentials: true,
methods: 'GET,PUT,POST,DELETE,UPDATE,OPTIONS',
optionsSuccessStatus: 200,

and here the frontend React:

const axiosClient = axios.create({
 baseURL: process.env.REACT_APP_BACKEND_URL,
 timeout: 1000 * 60 * 5,
 withCredentials: true,
 headers: {
'Content-Type': 'application/json',
}
 });

find attached screenshots from my browser after attempting my login request:

enter image description here

Console CORS wildcard error:

enter image description here

We can see that the response have " * " wildcard, but should not be. Thanks !


Solution

  • Finally solved the error, it's because we cant have app.enableCors() and cors: true in the bootstrap function co-existing. the cors: true from bootstrap will override all responses headers.

    async function bootstrap() {
    **cors: true**
      const app = await NestFactory.create<NestExpressApplication>(AppModule, {
        logger: ['error', 'warn', 'log', 'debug', 'verbose'],
      });