我是Ionic 4的新手。我想从API获取请求。请求需要令牌。因此,我尝试使用授权。但我得到这样的错误:
token
null
Access to XMLHttpRequest at 'http://xxx/api' from origin
'http://localhost:8100' has been blocked by CORS policy:
Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
这是我的代码 auth.service.ts :
getUserToken() {
this.loadToken();
const headers = new HttpHeaders()
.append('Authorization', 'Bearer' + this.authToken)
.append('Content-Type', 'application/json');
return this.http.get('http://xxx/api', {headers});
}
loadToken() {
console.log(this.authToken);
this.authToken = localStorage.getItem('token');
console.log(this.authToken);
}
这是 home.page.ts
ionViewWillEnter() {
this.isLoading = true;
this.authService.getUserToken().subscribe(() => {
this.isLoading = false;
});
}
myProxy.config.json
{
"name": "myApps",
"proxies": [
{
"path": "/tabs/tab1",
"proxyUrl": "http://xxx/api/user"
}
]
}
有人可以帮助我吗?非常感谢
答案 0 :(得分:0)
如果您使用的是移动应用,请尝试使用ionic-native HTTP。