405 Method Not Allowed despite CORS
Asked Answered
C

1

11

I am trying to develop a frontend application using Angular. Since I added the authorization header to the HTTP POST and GET requests, I'm getting 405 Method Not Allowed, although I seemingly allow everything on the server side.

enter image description here

The debugger in my browser Chrome says it's asking for Access-Control-Request-Method: POST and Access-Control-Request-Headers: authorization, my backend allows both, access-control-allow-methods: GET, POST and access-control-allow-headers: authorization, as well as access-control-allow-credentials: true.

I don't see what I'm missing here. The server is a node.js express server, the headers are set like this:

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Headers', 'authorization');

The frontend code (Angular 5) looks like this:

this.http.request('post', apiUrl, {
  headers: new HttpHeaders().set('Authorization', 'Bearer abc'),
}).subscribe(response => {
  // some code
});

Where this.http is an instance of Angular's HttpClient.

My frontend application is served from my localhost domain "http://frontend.localhost/app", my backend server is located at "http://backend.localhost".

My question is, am I missing some headers I have to set on my backend? Do I need to set some options in my frontend application?

Caddell answered 7/1, 2018 at 17:14 Comment(2)
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');, add 'OPTIONS' as well.Restrained
@TsvetanGanev I added 'OPTIONS' to the allowed methods, but the error message keeps the same.Caddell
C
13

I figured out my issue is not directly related to CORS. My backend is currently a GraphQL server only, which allows GET and POST requests.

If I add additional headers on the client side, the browser is checking for CORS via a preflight OPTIONS request, to the URL where the GraphQL server resides. This results in a 405 Method Not Allowed error produced by the GraphQL server, not by Express or the browser.

Caddell answered 7/1, 2018 at 17:45 Comment(1)
Simon, on a side-note, Access-Control-Allow-Credentials: true IS NOT allowed with Access-Control-Allow-Origin: *. If you're going to pass credentials (authorization header and/or cookies), you MUST specify a specific origin in the ACAO header - easiest to implement as Access-Control-Allow-Origin: {value of Origin request header}.Fumikofumitory

© 2022 - 2024 — McMap. All rights reserved.