无法在角度应用程序中获取API数据会抛出Access-Control-Allow-Origin

时间:2017-11-03 13:30:38

标签: angular cookies

我编写了用户服务,以便使用api调用获取用户信息。

user.service.ts

getBasicInfo(): Observable<any> {
            return this.http.get(this.config.apiUrl + 'api/supplier-basic-info/' + 'userID')
            .map(res => res.json());
        }

在组件中我写了这样的observable:

user.component.ts

getBasicInfo(){
    this._userService.getBasicInfo().subscribe(
      data => this.supplierInfo = data.results
    );
  }

当我尝试将html组件中的数据绑定为:

<div>{{getBasicInfo()}}</div>

然后我在控制台中收到错误:

Failed to load http://<SOME.IP.ADDRESS.>/api/supplier-basic-info/54: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

为什么我无法获取HTML中的数据。谁可以帮我这个事?后端开发人员将用户的详细信息存储在cookie中。我需要做什么来获取数据并使用Angular将其绑定在HTML页面中。因为我对基于Angular4组件的编程非常陌生。

感谢。

1 个答案:

答案 0 :(得分:1)

这与您的前端代码没有任何关系。你可以优化这个,但这将是另一个故事。

问题是CORS未激活。看看:CORS

您必须在服务器端配置中激活CORS。因为您没有指定您的技术,我无法帮助您获得确切的链接。只需google for&#34;在[您的服务器框架]中激活cors&#34; ;)