对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头
我正试图通过Angular应用程序5在Requestbin中执行POST,但我遇到了问题 .
我在localhost上运行我的应用程序,我认为由于这个原因,通信中存在错误 .
当我通过Postman运行帖子时,它正常工作 .
我究竟做错了什么?
执行以下方法时,发生以下错误:
const options = {
headers: new HttpHeaders({
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': '*'
})
};
newRequest() {
return new Promise((resolve, reject) => {
this.http.post('https://requestb.in/1nfocrm4', { 'name': 'User Test' }, options)
.subscribe((result: any) => {
resolve(result);
},
(response: any) => {
reject(response);
}
)
})
}
控制台开发人员工具出错:
Failed to load https://requestb.in/1nfocrm4: 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.
app.component.ts:21 HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
3 回答
在本地后端应用程序中,您需要启用
CORS
以允许角度应用程序访问数据 .**Allow-Control-Allow-Origin: *** 扩展名
我在Google Chrome中添加了一个扩展程序,并解决了错误,但现在它又返回了另一个错误
我对此的解决方案是:
在Google Chorme中安装名为 allow-control-allow-origin extension 的扩展程序,然后启用跨源 .
requestbin的响应是一个文本,所以我不得不在GET中传递一个参数