【发布时间】:2017-11-18 07:20:51
【问题描述】:
我在通过 Angular 2 typescript 访问 rest api 端点时遇到如下所述的“跨源请求被阻止”异常。我正在尝试学习 Angular 2,请帮我解决这个问题。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://xxxxxxxxx.com/place/countries. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
我的服务等级如下:-
import { Injectable } from '@angular/core';
import { Headers, Response, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
//import { Observable } from 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { HeaderOption } from '../model/header-option.component';
import { Country } from '../model/country.component';
import { BRAND_HEADERS, LEFT_HEADERS, HOME, PROFILE, LOGOUT, LOGIN} from './header-mock';
@Injectable()
export class HeaderService {
private headers = new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'});
private countriesUrl = 'http://XXXXXXXXXXXXXXX.com/place/countries';
constructor(private http: Http) {}
getCountries(): Observable<Country[]> {
//return this.http.get(this.countriesUrl, {headers: this.headers}).toPromise().then(response => response.json().records as Country[]).catch(this.handleError);
//return this.http.get(this.countriesUrl, this.headers).map((res:Response) => res.json()).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
return this.http.get(this.countriesUrl, this.headers).map((response: Response) => <Country[]> response.json()).do(data => console.log(JSON.stringify(data)));
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
getBrand():HeaderOption{
return BRAND_HEADERS;
}
getLeftHeader():HeaderOption[]{
return LEFT_HEADERS;
}
getHomeLink():HeaderOption{
return HOME;
}
getProfileLink():HeaderOption{
return PROFILE;
}
getLogoutLink():HeaderOption{
return LOGOUT;
}
getLoginLink():HeaderOption{
return LOGIN;
}
}
【问题讨论】:
-
它不是客户端..它的服务器阻止跨源请求...在服务器上修复它,客户端只显示服务器返回的错误
-
为什么服务器阻止它,当计划 URL 可从浏览器访问时。在服务器端需要做什么才能启用它..?
-
why server blocking it因为这就是 CORS 的全部意义 -
默认情况下,任何服务器都未启用 cors,您必须编写代码才能做到这一点...取决于您的服务器编写的语言,谷歌它,您应该得到一个解决方案。但首先尝试了解什么是 CORS,以及为什么默认禁用它是件好事
标签: angular promise angular2-services angular-http angular2-observables