【发布时间】:2018-07-05 12:04:53
【问题描述】:
我是 Angular 5 的新手,我想发送 http 请求,但它在检查元素中返回 CORS 错误。
错误
XMLHttpRequest 无法加载 http://example.com/account/create。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin '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);
}
【问题讨论】:
-
您能否提供有关 Web 服务器的信息(在您的情况下为 example.com)?它是如何设置的?
-
我没有配置网络服务器。在邮递员中它正在工作
-
如果你运行
curl -X OPTIONS http://example.com/account/create -i会得到什么(替换为你的实际服务器) -
@samsonthehero 非常感谢您的回复
-
您为 CORS 添加标头作为客户端您不能这样做 CORS
Access-Control-*的标头必须来自您的服务器,因此您需要修复服务器代码或获取其他代码来修复它。
标签: javascript xmlhttprequest angular2-services angular5