问题描述
我正在尝试使用 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
以及 access-control-allow-凭据:真实
.
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
.
我的前端应用程序来自我的本地主机域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.
如果我在客户端添加其他标头,浏览器将通过预检 OPTIONS 请求检查 CORS,到 GraphQL 服务器所在的 URL.这会导致 405 Method Not Allowed GraphQL 服务器产生的错误,而不是 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.
这篇关于405 方法不允许,尽管 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!