NestJS CORS issus when using GraphQL

後端使用nest框架,開啓了跨域資源共享,但是前端請求依然遇到問題

Access to XMLHttpRequest at 'http://161.489.630.200:9001/graphql/auth/login' from origin 'http://161.489.630.200:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 之前的項目中如下代碼是不會出現問題的

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

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

  app.useGlobalPipes(new ValidationPipe({ skipMissingProperties: true }));

  await app.listen(3000);
  console.log(`Application is running on: http://localhost:3000`);
}

bootstrap();

 但是這次因爲用到了Graphql,所以參照 https://stackoverflow.com/questions/50949231/nestjs-enable-cors-in-production 進行了如下修改,問題解決了。

// main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // cors
  app.enableCors({
    origin: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials: true,
  });

  app.useGlobalPipes(new ValidationPipe({ skipMissingProperties: true }));

  await app.listen(3000);
  console.log(`Application is running on: http://localhost:3000`);
}

bootstrap();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章