我有一个部署在IBM Cloud(Bluemix)上的NodeJS服务器,该服务器具有使用HTTPS公开的Restful服务。服务器还通过设置Authorization标头来期望Bearer Token。
服务器正在运行,我可以使用POSTMAN进行测试调用。令牌是否可用时,服务器将返回预期的响应。
由于授权标头的问题,我无法使我的Ionic应用程序(Ionic 4.1.2)成功调用该服务。
我正在使用HttpClient
,如下所示:
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
@Injectable()
export class MyService {
accessToken = 'here my bearer token';
url = 'https://mydeployedproject.eu-gb.mybluemix.net/api/myserviceendpoint';
constructor(private httpClient:HttpClient) {
}
getResultsFromBackend() {
console.log('Calling restful service: ' + url);
const headers = new HttpHeaders({
'Accept': 'application/json',
'accept-language':'en-eu',
'Authorization':'Bearer mybearertoken'
});
var response = this.httpClient.get(url,{headers})
.subscribe(response => console.log(response));
return response;
}
请注意:在服务端,我可以调试标头,并且可以看到当标头仅包含Accept
和accept-language
时标头的Accept和accept-language设置正确。
添加Authorization
头时,get调用中断了流程,并且get调用未正确执行,而不是服务器。
我目前正在使用 iOS模拟器和ionic cordova emulate ios --livereload -lc
在服务器端,我正在使用以下内容允许CORS
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
答案 0 :(得分:2)
该问题与服务器端(NodeJS)上允许CORS(跨域资源共享)标头有关。以下标头配置确实解决了该问题,并且ionic应用程序终于能够使用承载令牌成功请求后端。
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
next();
});