Search code examples
angularcorsnestjsangular-universal

CORS error while using Nest.js and server side rendered Angular Universal app


I have a server side rendered Angular Universal app using Nest.js. So they are running on the same origin, localhost:4200.

I have tried enabling CORS (with various cors-options) in the Nest.js app using:

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors(
  {
    origin: false,
    preflightContinue: true,
    methods: ['GET,POST,OPTIONS,DELETE,PUT'],
  }
)
app.setGlobalPrefix('api');
await app.listen(process.env['PORT'] || 4000);

}

Tried setting origin to: http://localhost:4200 without any success.

Also tried the simpler without success:

app.enableCors()

I'm getting the following errors in the web console:

Origin http://localhost:4200 is not allowed by Access-Control-Allow-Origin. Status code: 200 XMLHttpRequest cannot load https://www.google.com/ due to access control checks. Failed to load resource: Origin http://localhost:4200 is not allowed by Access-Control-Allow-Origin. Status code: 200 (www.google.com, line 0)

I'm simply trying to do a GET request using Angular HttpClient in my front-end:

  public fetchData(): Observable<any> {
    return this.httpClient.get('https://www.google.com')
  }

What am I missing?


Solution

  • you are properly enabling CORS in your backend, that means that client can make API requests to your backend from different origin than the backend's without the browser blocking the result.

    yet in your question, you are making requests from you frontend (which is assume was served from the backend's origin) to a different origin - google's. that means that google's backend is the one who needs to be configuring CORS, yet the endpoint you requested does not allow cross-origin and the request fails.

    to summary, even tho you have configured CORS on your backend, you are making request to a different backend which didn't allow CORS. because you have configured CORS on your backend, means that clients from different origin will successfully be able to make requests to your backend. you can verify that if you run the same script on different ports and make request from a client that was served from lets say port 4000 to backend that runs on port 4001.

    as suggested in the comments, to solve this issue specifically you need to proxy the request to google in your backend (which doesn't have the browser's CORS policy). in this way you will send an API call from your frontend to your backend which in turn will send the request to google and will return the result to your frontend.