Home > OS >  Angular - adding access-control-max-age header in the interceptor causing CORS error
Angular - adding access-control-max-age header in the interceptor causing CORS error

Time:03-09

I have requirement to prevent the OPTIONS request when calling APIs. After doing some research I got to know that adding access-control-max-age header will do the trick, but when I add it in my interceptor, I am getting CORS error for one of our API.

  if (token !== '') {
    if (!excludeUrls.map((x) => requestToForward.url.startsWith(x))[0]) {
      const tokenValue = this.userSecurityService.getBearerToken();
      requestToForward = req.clone({
        setHeaders: {
          Authorization: tokenValue,
          APIKEY: `${this.appConfig.config.apikey}`,
          'ACCESS-CONTROL-MAX-AGE': '86400'
        },
      });
    } else {
      requestToForward = req.clone({
        setHeaders: { APIKEY: `${this.appConfig.config.apikey}` },
      });
    }
  }

Am I doing this in correct way? I even tried adding it in a service file where I invoke the API call, if I add there, I don't see any CORS error, but still OPTIONS request is being called every time. Any suggestion on this? Thanks

CodePudding user response:

What you are attempting to do fundamentally will not work.

There is no way to stop the web browser from sending the pre-flight OPTIONS request. The pre-flight request is a browser security mechanism, and as such, you have no control over it from the client side.

The Access-Control-Max-Age request header indicates how long the results of the OPTIONS request may be cached, but the client has to send one in the first place for there to be something to cache, the effect is obviously temporary, and there's no absolute guarantee, AFAIK that another OPTIONS request won't be sent before the cache expiration time.

The only way to keep your clients from sending CORS pre-flight requests is to re-arrange things so that the browser doesn't consider the requests to be Cross-Origin (e.g. must be same domain and same port as the original 'page').

CodePudding user response:

It won't work, JS app cant do anything about is as CORS policy are enforced by the browser, not the app.

In order to get rid of preflights, your XHR requests has to be considered Simple requests or you have execute request on the same domain your application is deployed on (using backend proxy)

So, either make everything a "simple request" (only GET HEAD POST with narrow set of "standard headers" which excludes your API key header, and cannot be json) or setup a backend proxy that will proxy traffic and expose foreigh API on the same domain as the deployment.

  • Related