我正在尝试使用与Postman完美配合的API,但在我的角度2应用程序中无效。我对http://date.jsontest.com做了一个测试api,看看在angular2中http的所有内容是否正常工作。
我收到的错误消息: XMLHttpRequest无法加载https://tsp.touchstream.global/api/rest/stream_enable/a85a58c7/。预检响应中的Access-Control-Allow-Headers不允许使用请求标头字段X-TS-ID。
operations.service.ts
import {Injectable} from "@angular/core";
import {Http, Headers} from "@angular/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';
@Injectable()
export class OperationsService {
listSingleStream(channel) {
const streamKey = channel;
const url = 'https://tsp.touchstream.global/api/rest/stream_enable/' + streamKey +'/';
console.log(url)
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer ********key*********', //private keys
'X-TS-ID': '********key*********'
});
return this._http.get(url, {headers: headers})
.map(response => response.json())
.catch(error => Observable.throw(error.json()))
}}
touchstream.component.ts
import {Component, OnInit} from "@angular/core";
import {FormBuilder, ControlGroup, Validators, Control} from "@angular/common";
import {OperationsService} from "../operations.service";
import {Router} from "@angular/router/src/router";
import {ErrorService} from "../../error/error.service";
@Component({
moduleId: module.id,
selector: 'touchstream',
templateUrl: 'touchstream.component.html',
})
export class TouchstreamComponent implements OnInit {
singleChForm: ControlGroup;
channelInfo:string;
constructor(private _fb:FormBuilder, private _operationService: OperationsService, private _router: Router, private _errorService: ErrorService) {}
ngOnInit() {
this.singleChForm = this._fb.group({
channel: ['', Validators.required]
});
}
onSingleSearch() {
console.log(this.singleChForm.value.channel);
const channel = this.singleChForm.value.channel
this._operationService.listSingleStream(channel)
.subscribe(
data => this.channelInfo = JSON.stringify(data),
error => console.log('error'),
() => console.log(this.channelInfo)
)
}
}
答案 0 :(得分:0)
这是CORS Wiki link
的问题如果您可以通过https://tsp.touchstream.global/api/rest/stream_enable/a85a58c7/访问服务器,则可以修改其CORS设置以接受上述标题字段。
但是反向代理对该服务器的所有请求会更容易。您可以将服务器配置为代理传递/ tsp-api / *的所有请求到https://tsp.touchstream.global/api/*。在您的angular2应用中,只需请求' / tsp-api / rest / stream_enable /' + streamKey +' /'。这样,您的请求将具有相同的来源,避免所有CORS头痛
您可能希望使用nginx或apache2作为服务器引擎。这些引擎完美地处理代理和反向代理。