我是 Angular 5 的新手,我想发送 http 请求,但它在检查元素中返回 CORS 错误。
错误
XMLHttpRequest 无法加载 http://example.com/account/create。对预检请求的响应未通过访问控制检查:请求的资源上不存在"访问控制允许源"标头。因此,不允许访问源"http://localhost:4200"。响应具有 HTTP 状态代码 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
等(访问它。
服务器需要提供这些标头才能访问其资源。
Mozilla在这里写得很好。
//添加 CORS 标头。
Example :
const Url = 'http://localhost:3000/';
const headers = new Headers;
const body = JSON.stringify(
{
title: "data"
});
headers.append('Access-Control-Allow-Origin', '*');
this.http.post(Url, body, { headers: headers })
.pipe(map(res => res))
.catch(err => err);
// you can also use HTTP headers
import { HttpHeaders } from '@angular/common/http';
let header = new HttpHeaders();
header.set('Access-Control-Allow-Origin', '*');
你确定在你的apiUrl变量发送中得到了 http://部分作为postFormData函数的参数。在使用HttpClient函数时,http://部分看起来非常重要。
CORS 只能使用 Access-Control-Allow-Origin
标头在服务器端进行管理。
在您的情况下,在 localhost:4200
为 Angular 客户端提供服务时,您对此标头的值有 2 个选项:
- 添加
*
- 这将启用所有源(不推荐在生产环境( - 添加
localhost:4200
(包括端口!( - 这将明确授予仅到服务器的域+端口