Chulhwa Han
Chulhwa Han

Reputation: 21

Nest js - Cors error about 'access-control-allow-origin'

I'm currently developing a reservation system and the authentication I use is JWT and saving it in my cookie. However, I got a error about cors like this.

guestinfo:1 Access to fetch at 'https://localhost:4000/auth/login' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'

error 1

Nest JS code

  app.use(function (req: Request, res: Response, next: NextFunction) {
    res.header('Access-Control-Allow-Origin', [
      'https://127.0.0.1:3000/',
      'https://localhost:3000/',
      'https://127.0.0.1:3000',
      'https://localhost:3000',
    ]);
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept',
    );
    next();
  });

  app.enableCors({
    origin: [
      'https://127.0.0.1:3000/',
      'https://localhost:3000/',
      'https://127.0.0.1:3000',
      'https://localhost:3000',
    ],
    credentials: true,
    // methods: ['GET', 'POST'],
    // allowedHeaders: ['Content-Type', 'Authorization'],
    // maxAge: 86400,
  });
  await app.listen(4000);

React Code

  const login = async () => {
    const requestOptions = {
      credentials: 'include',
      withCredentials: true,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      path: '/',
      body: JSON.stringify({
        id: "ID",
        password: "PASSWORD"
      })
    };

I'd tried credentials, https, httpOnly, Secure, sameSite, expires options. But these didn't working and still get in. In my opinion, this problem is 'access-control-allow-origin'. But it isn't changed.

How can I solve this error? Please help me.

Upvotes: 1

Views: 1415

Answers (1)

samolusola
samolusola

Reputation: 82

You don't need to set res.header, you can set cors configuration just by using app.enableCors. I suspect that those two configurations are conflicting, make use of app.enableCors

Make sure you provide the origin and the methods allowed.

This should work:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors({
    origin: [
      'https://127.0.0.1:3000/',
      'https://localhost:3000/',
      'https://127.0.0.1:3000',
      'https://localhost:3000',
    ],
    methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
    credentials: true,
  });
  await app.listen(4000);
}
bootstrap();

Upvotes: 1

Related Questions