【问题标题】:token not being sent in pre-flight request Ionic2未在飞行前请求 Ionic2 中发送令牌
【发布时间】:2018-04-21 12:05:45
【问题描述】:
我正在使用 DRF 作为 API 服务在 Ionic 2 中开发一个应用程序。出于身份验证目的,我使用的是 JWT。我将身份验证令牌与每个请求一起发送为Authorization: jwt [token]。在 Postman 中,API 工作正常。
现在,当我在浏览器中对其进行测试时,它无法正常工作,我发现它可能无法正常工作,因为 JWT 身份验证令牌没有在 OPTIONS 请求中作为飞行前发送。那么我该如何解决这个问题。
【问题讨论】:
标签:
django
angular
ionic2
django-rest-framework
cors
【解决方案1】:
实际上问题在于,如果没有授权令牌,OPTIONS api 将无法读取,因此我们为OPTIONS 和 GET api 添加了readonly Auth 级别。
【解决方案2】:
在 Ionic 最新版本中,如果您使用 ionic serve commnad,那么您必须使用代理来防止 Preflight 和 CORS 问题,
首先在ionic.config.json文件中添加API路径和网址
{
"name": "APP-NAME",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://example.com/api"
}
]
}
现在,在从 http 调用您的 API 时,请使用 /api URL 而不是 http://example.com/api 之类的,
....
this.http.post('/api', data, {headers:headers}).map(res=>res.json()).subscribe(data=>{
console.log(data)
}, err=>{
console.log("Error!:", err.json());
});
....
进行上述更改后,您必须重新运行命令ionic serve。
不过,如果您遇到问题,请参考 Handling CORS Issues In Ionic 和 https://ionicframework.com/docs/cli/configuring.html
【解决方案3】:
在 CORS 预检 OPTIONS 响应中,Cross-Origin-Allow-Headers 应与请求的响应相匹配。
Cross-Origin-Allow-Headers: Authorization