【发布时间】:2017-09-06 17:00:48
【问题描述】:
我正在尝试连接到 API,但出现错误。
XMLHttpRequest 无法加载 https://valgresultat.no/api/。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 访问。
我的 proxy.config.json
{
"/api/": {
"target": {
"host": "valgresultat.no",
"protocol": "http:",
"port": 80
},
"secure": false,
"changeOrigin": true,
"logLevel": "info"
}
}
我的 app.component.ts
import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
private apiUrl = '/api/';
data: any = {};
constructor(private http: Http) {
console.log('Hello fellow user');
this.getContacts();
this.getData();
}
getData() {
return this.http.get(this.apiUrl).map((res: Response) => res.json())
}
getContacts() {
this.getData().subscribe(data => {
console.log(data);
this.data = data
})
}
}
【问题讨论】:
-
这与角度无关,这更像是服务器配置。您需要在提供 API 的服务器上启用 CORS。
-
没错,这是一个CORS问题,看看developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS。您应该使用正确配置的请求/响应标头启用方法 OPTIONS 响应。
标签: angular