如何在Angular 5中解决CORS问题HTTP请求 [英] How to fix CORS issue http request in Angular 5

查看:427
本文介绍了如何在Angular 5中解决CORS问题HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular 5的新用户,我想发送http请求,但它在inspect元素中返回CORS错误.

I am new in Angular 5, and I want to send http request but it return CORS error in inspect element.

错误

XMLHttpRequest无法加载 http://example.com/account/create .对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:4200 .响应的HTTP状态码为403.

XMLHttpRequest cannot load http://example.com/account/create. Response to preflight request doesn't pass access control check: 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.

下面是我的代码:

postFormData(apiUrl: string, value: Object): Observable<any> {
const body = value;
const headers = new Headers();
const utcOffset = -(new Date().getTimezoneOffset());
headers.append('Content-Type', 'application/json');
headers.append('utc-offset', utcOffset.toString());
headers.append('platform', 'WEB');
headers.append('app-version', '1.00');
headers.append('version', '1.0');
headers.append('accept', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

if (localStorage.getItem('user')) {
  const user = JSON.parse(localStorage.getItem('user'));
  headers.append('token', user.token);
  headers.append('session', user.session);
}
// const options = new RequestOptions({ headers: headers });
return this.http.post(apiUrl, body, { headers: headers })
  .map(this.extractData)
  .catch(this.handleServerError);
}

推荐答案

CORS是浏览器使用的一种工具,它可以防止一个来源(在您的情况下为localhost)从另一个地方(example.com)访问资源,而无需服务器明确声明您可以通过Access-Control-Allow-Origin等CORS标头访问它.

CORS is a tool employed by browsers to prevent one origin (localhost in your case) from accessing resources from another (example.com) without the server explicitly saying you can access it via CORS headers like Access-Control-Allow-Origin and others.

服务器需要提供这些标头,以便您访问其资源.

It is the server that needs to provide those headers in order for you to access it's resources.

Mozilla在此处上写得很好

Mozilla has a good write up on it here.

这篇关于如何在Angular 5中解决CORS问题HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆