问题
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.
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?
回答1:
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.
来源:https://stackoverflow.com/questions/48139612/405-method-not-allowed-despite-cors