我得到了#34;跨域请求被阻止"通过Angular 2打字稿访问rest api终点时下面提到的异常。我试图学习角度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;
}
}
答案 0 :(得分:0)
如果您有节点/快递应用,则必须启用CORS :
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
});
答案 1 :(得分:0)
您的问题是服务器端。服务器不允许您所在域的浏览器发出请求,我假设“ localhost:4200”,则可以将Access-Control-Allow-Origin标头添加到服务器响应标头中。https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin 如果您只是测试和学习,则可以将此插件https://addons.mozilla.org/en-GB/firefox/addon/cors-everywhere/用于Firefox浏览器或其他浏览器。