gpt4 book ai didi

cors - 在 NestJs 中启用 Cors

转载 作者:行者123 更新时间:2023-12-04 11:24:43 27 4
gpt4 key购买 nike

我想使用 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();

最佳答案

在您的 main.ts , 编辑 bootstrap 函数如下启用 CORS

const app = await NestFactory.create(AppModule, { cors: true });

或者
const app = await NestFactory.create(ApplicationModule);
app.enableCors();

此方法可帮助您为 cors 传递额外的参数

阅读更多关于 CORS here

关于cors - 在 NestJs 中启用 Cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502045/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com