[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
CORS simply does not work regardless of how I enable it.
const app = await NestFactory.create(AppModule, { cors: true });
const app = await NestFactory.create(AppModule, { cors: {corsOptions} });
app.enableCors() ;
app.enableCors({corsOptions})
app.use(cors());
HTTP OPTIONS requests just end up with a 404
This is during development and not production. I've checked whether or not compiling to javascript was successful as well.
CORS should be enabled.
Create a new project and just attempt to enable CORS with previously mentioned methods above.
Nest version: 5.3.10
For Tooling issues:
- Node version: 10.6.0
- Platform: Windows 7, MacOS 10.14
Others:
You have a reproducable repo? I can't seem to reproduce this error.
No. I'm probably testing it incorrectly. Let me do more homework and possibly reopen
I can confirm now. That said, it might not be a bug but a config issue with both my Mac and Windows machines.
curl -H "Origin: http://localhost:4200" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: X-Requested-With" -X OPTIONS --verbose http://localhost:3000
* Rebuilt URL to: http://localhost:3000/
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 3000 (#0)
> OPTIONS / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.55.0
> Accept: */*
> Origin: http://localhost:4200
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: X-Requested-With
>
< HTTP/1.1 404 Not Found
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 67
< ETag: W/"43-S8iZMBrmDLr0nVizyxv2eu1ojjU"
< Date: Fri, 28 Sep 2018 22:17:34 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{"statusCode":404,"error":"Not Found","message":"Cannot OPTIONS /"}
I'm getting the "Response for preflight does not have HTTP ok status" error
I can share the repo privately if possible
Please share the repo, I can not reproduce the issue either.
Probably a config issue on my end then. I'll post on StackOverflow. I'll try to share a repo this week.
I was updating main.hmr.ts instead of main.ts.
im having this same issue after upgrading to the latest
@williamchristophercooley I had this problem due to user error. I made my changes to a file called main.hmr.ts, when the actual file that I needed to change was main.ts.
It's done in express via app.options('*', cors())
. It seems to me that NestJS does not support this.
@kamilmysliwiec any ideas how could it be implemented?
https://docs.nestjs.com/techniques/security "CORS" chapter
@kamilmysliwiec it does not enable preflight request handling.
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
https://www.npmjs.com/package/cors#enabling-cors-pre-flight
You can pass additional parameters to configure your cors middleware app.enableCors(options)
. If something doesn't work for you, I'd suggest asking on StackOverflow
app.use(cors())
does not enable pre-flight request.
Just edited my answer, thanks. Simply customize cors
behavior by passing options object:
https://github.com/expressjs/cors#configuration-options
I totally forgot that cors() supports configuration options. Thank you.
However, most of these options seem to not make any effect. (5.6.2)
const app = await NestFactory.create<NestFastifyApplication>(ApplicationModule, new FastifyAdapter());
const options = {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204,
"credentials":true
}
//app.use(cors(options))
app.enableCors(options)
these codes are not working again in version [email protected]
@blueway Try adding the allowedHeaders
config option
app.enableCors({
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
allowedHeaders: "Content-Type, Accept",
});
If you still struggling with origin has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
use this conf
app.enableCors({
origin: true
})
Dunno why { origin: '*' }
does not work
Here is link to question on Stackoverflow
Looks like something wrong with big amount requests. Because first 20 requests is OK, but then always appear the same error for me:
Access to XMLHttpRequest at 'https://my-back-end-server/v1/tasks' from origin 'https://my-server.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
bundle.js:531
I've tried everything :(
I can use PAW or Postman and make API calls to my nest project, but if I use my mobile app, it fails.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
}
bootstrap();
Here is link to question on Stackoverflow
Looks like something wrong with big amount requests. Because first 20 requests is OK, but then always appear the same error for me:
Access to XMLHttpRequest at 'https://my-back-end-server/v1/tasks' from origin 'https://my-server.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. bundle.js:531
Getting the same.... some requests are then others are not
const allowedOrigins = [
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
'http://localhost:8100',
];
// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
}
}
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
app.enableCors({ ...corsOptions });
await app.listen(3000);
}
bootstrap();
I have the same issue as @tskweres. Currently developing a mobile app using nest and ionic. When my Ionic app is deployed on my phone, it can't communicate with my NestJS server on the same WIFI network. Tried to access my server URL directly on my phone's browser, it doesn't work.
I have tested various cors origin configurations such as *
, /.+/
, and my phone's IP address, but nothing seems to work.
Same issue debugging from Ionic, Web and Mobile:
Access to XMLHttpRequest at 'https://blzblzblz.appspot.com/api/login/register' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
@chaostheory can you reopen this issue please? I'm getting this warning from Android and Chrome:
Access to XMLHttpRequest at 'https://my-app.appspot.com/api/users/userFile' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is the code I'm using to enable CORS:
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
cors: true
});
app.enableCors();
Also, I tried a list of allowed origins too:
const allowedOrigins = [
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'https://my-app'
]
app.enableCors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.some(o => origin.startsWith(o))) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
},
preflightContinue: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true
});
The endpoint I'm debugging is a multipart/form-data
:
@Post('userFile')
@HttpCode(HttpStatus.OK)
@UseGuards(AuthGuard())
@UseInterceptors(FileFieldsInterceptor([
{ name: 'data', maxCount: 1 }
], {
limits: {
fieldSize: 10 * 1024 * 1024,
fileSize: 10 * 1024 * 1024
},
fileFilter: function (req, file, cb) {
if (file.mimetype !== 'image/jpeg') {
return cb(new Error('Only jpg is allowed'), false)
}
cb(null, true)
}
}))
@ApiConsumes('multipart/form-data')
async addUserFile(@Request() req) {...}
Any help is really appreciated! 馃檹
Issue still here, tried everything from above.
It seems the following code works. But passing CorsOptions obj or use app.enableCors(options) won't work. When the browse try to run OPTIONS method, nestjs spits 404 error.
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
cors: true
});
In my case CORS is working for application/json with POST and PUST requests, but I'm having issues in multiple devices uploading files with a multipart/form-data, getting a lot of errors related with CORS.
Any help would be appreciated! 馃憤
In my case CORS is working for application/json with POST and PUST requests, but I'm having issues in multiple devices uploading files with a multipart/form-data, getting a lot of errors related with CORS.
Any help would be appreciated! 馃憤
I am also experiencing this. Using multipart/form-data throws an error Access to XMLHttpRequest at 'http://localhost:5030/upload-file' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my configuration
const app = await NestFactory.create(AppModule);
const cors = {
origin: [
'http://localhost:4200',
'http://localhost:5030',
'http://localhost',
'*',
],
methods: 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
allowedHeaders: [
'Accept',
'Content-Type',
'Authorization',
]
};
app.enableCors(cors);
Any help will be appreciated.
I thought I had CORS error as well, but it turns out nginx has a low max body size for FormData. Check your nginx error log to see if that's the case and make sure you have client_max_body_size 10M
CORS is generally not handled by nginx itself. The app.enableCors(options);
seems to work as intended.
In my case the issue was because I was running nest from an azure functions instance. If you are using AWS Lambda or another similar implementation you may need to adjust the hosting service's configuration as well. I updated local.settings.json and it worked like a charm.
Edit: in local.settings.json
"Host": {
"CORS": "*"
}
Same here, above does works for me, postman is fine but not front end requests
Same here, above does works for me, postman is fine but not front end requests
Ok my issue was that I was posting to 'localhost:3000', but if I post to 'http://localhost:3000', it's fine...
Most helpful comment
these codes are not working again in version [email protected]