【发布时间】:2017-01-29 00:37:43
【问题描述】:
我在 Angular 2 中试图连接到一个我没有访问服务器端的 API。 我知道这个 API 和令牌可以正常工作,因为我将现有的 PHP 应用程序转换为 Angular。
这里是 myapp.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class DxdService {
private apiUrl = 'https://path/to/my/api/';
constructor(private _http: Http){
}
createAuthorizationHeader(headers: Headers) {
headers.append('X-Auth-Token','myvalidkey');
}
getValueFromApi(){
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this._http.get(this.apiUrl, headers)
.map(res => res.json());
}
}
这个总是返回
GET https://path/to/my/api/ 401 (Unauthorized)
XMLHttpRequest cannot load https://path/to/my/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The response had HTTP status code 401.
我在这里想不通的是,我设置标头 x-auth-token 的方式是错误的,还是我与 Access-Control-Allow-Origin CORS 问题作斗争。
考虑到我无法访问服务器端更改Access-Control-Allow-Origin 标头响应,如果我设置标头的方式正确,我该如何继续在本地开发?
【问题讨论】: