尽管有CORS,但不允许使用405方法 [英] 405 Method Not Allowed despite CORS
问题描述
我正在尝试使用Angular开发前端应用程序。由于我将授权标头添加到HTTP POST和GET请求,我得到 405 Method Not Allowed ,虽然我似乎允许服务器端的所有内容。
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.
浏览器中的调试器Chrome说它要求 Access-Control-Request-Method:POST
和 Access-Control-Request-Headers:authorization
,我的后端允许两者, access-control-allow-methods:GET,POST
和 access-control-allow-headers:authorization
,以及as access-control-allow-credentials:true
。
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
.
我看不到我在这里缺少什么。服务器是node.js express服务器,标头设置如下:
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');
前端代码(Angular 5)如下所示:
The frontend code (Angular 5) looks like this:
this.http.request('post', apiUrl, {
headers: new HttpHeaders().set('Authorization', 'Bearer abc'),
}).subscribe(response => {
// some code
});
其中 this.http
是一个实例Angular的 HttpClient
。
Where this.http
is an instance of Angular's HttpClient
.
我的前端应用程序是从我的localhost域提供的 http://frontend.localhost/app ,我的后端服务器位于 http://backend.localhost 。
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?
推荐答案
我发现我的问题是不是与CORS直接相关。我的后端目前只是一个GraphQL服务器,允许GET和POST请求。
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.
如果我在客户端添加额外的标头,浏览器会通过预检检查CORS OPTIONS 请求,指向GraphQL服务器所在的URL。这会导致GraphQL服务器产生 405 Method Not Allowed 错误,而不是Express或浏览器。
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.
这篇关于尽管有CORS,但不允许使用405方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!