Angular Firebase函数中的CORS
问题是功能被CORS阻止: “”已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头 我还在Firebase主持了一个项目。但它也不起作用。被相同的错误阻止 我的服务器代码:Angular Firebase函数中的CORS,angular,firebase,google-cloud-functions,Angular,Firebase,Google Cloud Functions,问题是功能被CORS阻止: “”已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头 我还在Firebase主持了一个项目。但它也不起作用。被相同的错误阻止 我的服务器代码: const cors = require('cors')({origin: true}); exports.myfunction = functions.https.onRequest( (req: any, response: any) => { retu
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);
});
let config={
标题:{
“内容类型”:“应用程序/json”,
“访问控制允许来源”:“*”,
}
}
this.http.post(URL,{data:'hello'},config).subscribe(res=>{
控制台日志(res);
});
请帮忙。我头痛。您需要在函数中设置访问控制允许-*标题,以匹配您想要接受的请求 下面是在CORS请求中从Node.js编写的CORS函数的示例:
exports.corsEnabledFunction = (req, res) => {
// Set CORS headers for preflight requests
// Allows GETs from any origin with the Content-Type header
// and caches preflight response for 3600s
res.set('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
} else {
res.send('Hello World!');
}
};
您需要将托管服务器的URL硬编码到客户端
因此,在Angular中,您将拥有连接到后端api端点的服务。在这里,“api url”常量必须是托管方或托管服务器的url。CORS必须在服务器上接受,而不是在客户端。这是服务器代码您的客户端是否有必要的头?我现在在问题中包括客户端代码您似乎在做大量手动响应头操作,但这就是
CORS
中间件是为您而设计的。请参见此处的示例~和此处的问题remains@JhonDoe硬编码托管服务器的URL有效吗?