后端使用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();