I want to use a NestJs api, but I get the same error message in each 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.
My frontend is an Angular, where I have a simple fetch
:
fetch('http://localhost:3000/articles')
.then((res) => {
console.log(res);
});
I tried these options in my NestJs - but none of them seem to work:
Attempt 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();
Attempt B
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
}
bootstrap();
Attempt C
async function bootstrap() {
const app = await NestFactory.create(AppModule, {cors: true});
await app.listen(3000);
}
bootstrap();
CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
To enable CORS on NGINX, you need to use the add_header directive and add it to the appropriate NGINX configuration file. to allow access from any domain.
You can test your API's CORS configuration by invoking your API, and checking the CORS headers in the response. The following curl command sends an OPTIONS request to a deployed API.
On your main.ts
, edit bootstrap function as follows to enable CORS
const app = await NestFactory.create(AppModule, { cors: true });
Or
const app = await NestFactory.create(ApplicationModule);
app.enableCors();
This method helps you to pass additional params for cors
Read more about CORS here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With