如何将标头添加到针对跨域API的OPTIONS请求中?
How can I add headers to the OPTIONS request made towards a cross-domain API?
我要使用的API要求在所有请求上都将JWT令牌设置为Authorization标头.
The API I'm working against requires a JWT token set as Authorization header on all requests.
当我尝试访问API时,Angular首先执行一个OPTIONS请求,该请求与我为真实"请求设置的标头无关,如下所示:
When I try to access to the API Angular first performs an OPTIONS request that doesn't care about my headers that I setup for the "real" request like this:
this._headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer my-token-here' }); return this._http .post(AppConfig.apiUrl + 'auth/logout', params, {headers: this._headers}) ... ...如果未提供令牌,则API返回HTTP状态401,并且Angular认为OPTIONS请求失败.
When no token is provided, the API returns HTTP status 401 and Angular thinks the OPTIONS request fails.
推荐答案根据CORS 排除执行预检请求时的规范用户凭证.
According to the CORS specification when a preflight request is performed user credentials are excluded.
(...)使用方法OPTIONS,并具有以下附加约束:
(...) using the method OPTIONS, and with the following additional constraints:
- (...)
- 排除作者请求标头.
- 排除用户凭据.
- (...)
- (...)
- Exclude the author request headers.
- Exclude user credentials.
- (...)
(重点是我的)
考虑到这一点,问题似乎出在API方面,应在不需要身份验证的情况下接受OPTIONS请求.
With this in mind, the problem seems to be on the API side of things, which should be accepting OPTIONS requests without requiring authentication.
更多推荐
将身份验证添加到OPTIONS请求中
发布评论