0

I have an angulat http interceptor that is trying to add Authorization headers to a request but when the code run the resulting request is not what I expect, the method is changed from POST to OPTIONS and I get an error like this :

Access to XMLHttpRequest at 'http://localhost/authorization/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

@Injectable()
export class DlkmInterceptor implements HttpInterceptor {

 constructor() {
 }

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   if (request.url === authConfig.tokenEndpoint && request.method === 'POST') {
     let authData = window.btoa(authConfig.clientId + ':' + authConfig.dummyClientSecret);
     request = request.clone({
       setHeaders: {
         'Content-Type': 'application/x-www-form-urlencoded',
         'Authorization': 'Basic ' + authData
       }
     });
     return next.handle(request);

   } else {
     request = request.clone({});
     return next.handle(request)
   }

 }
}

1 Answer 1

2

This is expected behavior. It is due to the Cross Origin Policy of browser.

Since you are requesting a resource from the domain other the one on which you Angular Application is hosted, so browser will follow the Cross Origin Policy

When you request a resource from a different origin, the browser first checks to see that you can actually request that resource or not by sending OPTIONS request also known as preflight request

You need to allow the headers in your backend server in order for preflight request to be successful, when the preflight request is successful, you browser will make the actually request.

You can learn more about this topic here

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but if I remove the code that add's the headers I got the POST request as expected !!
@HamidIng Thats's because the interceptor added the Authorizationheader, so this is not a 'simple' request anymore and so the browser needs to send a preflight request first: developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
@asim-hashmi and david thanks a lot for your help I did some modifications to backend source code to allow CORS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.