【发布时间】:2020-02-12 17:27:39
【问题描述】:
问题是函数被CORS阻塞:
“http://localhost:8100”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我还在 Firebase 中主持了一个项目。但它也不起作用。被相同的错误阻止。
我的服务器代码:
const cors = require('cors')({origin: true});
exports.myfunction = functions.https.onRequest( (req: any, response: any) => {
return cors(req, response, () => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.set('Access-Control-Allow-Methods', 'POST');
response.set('Access-Control-Allow-Headers', 'Content-Type');
response.set('Access-Control-Max-Age', '3600');
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Credentials', 'true');
response.status(200).send('hello world');
});
}
我的客户代码:
let config = {
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
}
}
this.http.post<any>(URL, {data: 'hello'},config).subscribe(res => {
console.log(res);
});
请帮忙。我的头好痛。
【问题讨论】:
-
CORS 必须在服务器而不是客户端上接受
-
这是服务器代码
-
您的客户是否有必要的标头?
-
我现在在问题中包含客户端代码
-
您似乎在进行大量手动响应标头操作,但这就是
cors中间件旨在为您做的事情。请看这里的例子~firebase.google.com/docs/functions/…和这里~firebase.google.com/docs/functions/…
标签: angular firebase google-cloud-functions