【发布时间】:2020-02-18 11:20:37
【问题描述】:
我想使用 NestJs api,但在每个 fetch 中都收到相同的错误消息:
Access to fetch at 'http://localhost:3000/articles' from origin 'http://localhost:4200' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我的前端是一个 Angular,我有一个简单的fetch:
fetch('http://localhost:3000/articles')
.then((res) => {
console.log(res);
});
我在我的 NestJs 中尝试了这些选项 - 但它们似乎都不起作用:
尝试A
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
allowedHeaders: 'Content-Type, Accept',
});
await app.listen(3000);
}
bootstrap();
尝试 B
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
}
bootstrap();
尝试 C
async function bootstrap() {
const app = await NestFactory.create(AppModule, {cors: true});
await app.listen(3000);
}
bootstrap();
【问题讨论】:
-
nestjs 使用 expressjs/cors github.com/expressjs/cors 中的 cors 模块。
origin: true属性用于每个路由以启用该特定路由的 cors。由于这是一个普遍的变化,我想我会尝试将其更改为origin: '*'以查看它是否有效。最终它应该是发起请求的域 -
@VladNeacsu 同样是
'*'或'localhost'或'localhost:4200' -
一定有一个不相关的问题,因为您的代码中的第二个示例
app.enableCors();似乎工作正常。您是否尝试在更改后重新启动应用程序?此外,端口无关紧要,并且由于错误您没有发出跨域请求 -
响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?
-
这能回答你的问题吗? NestJS enable cors in production