问题是这个函数被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);
});请帮帮忙。我的头好痛。
发布于 2019-10-17 15:48:45
您需要在函数中设置Access-Control-Allow-*标头,以匹配您想要接受的请求。
以下是一个CORS函数的示例,该函数是在CORS请求时从GCP documentation用Node.js编写的:
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!');
}
};发布于 2019-10-19 03:36:10
您需要将托管服务器的URL硬编码到客户端。
因此,在Angular中,您将拥有连接到后端api端点的服务。在这里,'api url‘常量必须是主办方或托管服务器的URL。
https://stackoverflow.com/questions/58404716
复制相似问题