【问题标题】:Angular, receiving data but getting CORSAngular,接收数据但获取 CORS
【发布时间】:2018-05-04 02:58:47
【问题描述】:

所以我不断收到此错误:

在我的其他 Angular 项目中,我在任何 POST 或 GET 请求之前向名为 OPTIONS 的服务器发送了一个预检请求,我注意到在这种情况下它丢失了,并且服务器正确响应了请求,但我无法访问它,因为错误被抛出,我无权访问数据。

我的服务有下一个实现:

  login(user) {
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
const body = new URLSearchParams();
body.set('grant_type', 'password');
body.set('username', user.username);
body.set('password', user.password);
return this._http.post('http://thevotechain.azurewebsites.net/Token', body, { headers: headers })
  .map((response: Response) => {
    return response.json();
  });

}

帮助。

【问题讨论】:

  • 后端 API 使用什么。哪种语言,服务器?
  • @AshishRanjan 我们正在使用 ASP .NET

标签: angular cors


【解决方案1】:

在您的 API 中设置带有键的响应标头:

Access-Control-Allow-Origin

localhost:4200 为例。

当你设置为localhost:4200时,你说这个前端应用可以访问我。

您也可以将其设置为*,这将使任何前端应用程序都可以使用您的API。

【讨论】:

  • 但是不应该有一个对 API 的 OPTIONS 请求吗?
  • @RichyST:您不发送选项请求,您的浏览器会发送。请查看此链接,查看浏览器将发送选项请求的请求类型。 developer.mozilla.org/en-US/docs/Web/HTTP/CORS
猜你喜欢
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 2015-12-11
  • 2018-03-26
  • 1970-01-01
  • 2015-08-06
  • 2021-12-16
相关资源
最近更新 更多