此服务从
向外部api导入{Injectable}发出http请求'@angular/core';
import { HttpModule,Http } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
@Injectable()
export class MyDataServiceService {
constructor(private http:Http) {}
getData(){
return this.http.get('http://stats.nba.com/stats/leaguedashplayerbiostats/?PerMode=Totals&Season=2016-17&LeagueID=00&SeasonType=Playoffs');
}
}
但是我收到了错误'solicitud desde otro origen bloqueada: la política de mismo origen impide leer el recurso remoto en http://stats.nba.com/stats/leaguedashplayerbiostats/?PerMode=Totals&Season=2016-17&LeagueID=00&SeasonType=Playoffs (razón: falta la cabecera CORS 'Access-Control-Allow-Origin').'
它说我的请求已被阻止,因为错过了CORS标头。
如果我不想使用后端,我该如何解决?
答案 0 :(得分:0)
CORS设置主要有一些方面:allowed_orign \ allowed_method \ allowed_header。您的错误提示似乎是允许的。 可以在nginx或app容器中添加cors设置。 来自https://enable-cors.org/server_nginx.html的nginx cors设置示例:
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}
}