405 Method Not Allowed despite CORS

妖精的绣舞 提交于 2019-12-31 02:26:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!