如何修复 Angular 5 中的 CORS 问题 http 请求 [英] How to fix CORS issue http request in Angular 5

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

问题描述

我是 Angular 5 的新手,我想发送 http 请求,但它在检查元素中返回 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"标头.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)的资源,而服务器没有明确告诉您可以通过 CORS 标头(如 Access-Control-Allow-Origin 等)访问它.

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天全站免登陆