参见英文答案 > How does Access-Control-Allow-Origin header work? 13个
> How to allow CORS? 24个
我在我的离子应用程序中使用Angular 5.我试图从我的代码中调用一个端点
ngOnInit(): void {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
this.httpClient.get('https://abc-66b76.cloudfunctions.net/getBillNo', {
headers: {
'Access-Control-Allow-Origin': '*'
}
}).subscribe(data => {
console.log('firebase bill No: ', data);
this.bill.billNo = data.billNo;
})
}
当我的页面加载时,上面的代码被调用,在Chrome浏览器控制台中我得到以下错误:
Failed to load 07002: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘07003’ is therefore not allowed access.
但是,如果我在我的Chrome浏览器中检查我的网络选项卡,我可以看到它已经命中服务器并得到了响应.
谁能帮我解决这个问题.
My Backend is firebase functions.
解决方法:
您需要在服务器端设置响应标头.
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'x-access-token,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
if (req.method == 'OPTIONS') {
res.status(200).json();
} else {
next()
}
});
希望这个答案对你有所帮助.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。