我正在开发一个 React 项目,我用 React.js 制作了前端并将其托管在 Firebase 上。我想在后端使用 firebase 云函数,所以我正在尝试它,但问题是我不断收到 CORS 错误。这正是我收到的错误。我可以在开发者工具的问题部分看到这一点。
`A 'cache-control' header is missing or empty.`
`Resource should use cache busting but URL does not match configured patterns.`
`Static resources should use a 'cache-control' header with 'max-age=31536000' or more.`
`Static resources should use a 'cache-control' header with the 'immutable' directive.`
`Ensure CORS response header values are valid`
`Response should include 'x-content-type-options' header.`
这是我的函数(function/index.js)
/**
* Import function triggers from their respective submodules:
*
* const {onCall} = require("firebase-functions/v2/https");
* const {onDocumentWritten} = require("firebase-functions/v2/firestore");
*
* See a full list of supported triggers at https://firebase.google.com/docs/functions
*/
const {onRequest} = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
// Create and deploy your first functions
// https://firebase.google.com/docs/functions/get-started
const functions = require("firebase-functions");
exports.helloWorld = onRequest(
{cors: true},
(request, response) => {
logger.info("Hello logs!", {structuredData: true});
response.send("Hello from Firebase!");
});
exports.bigben = functions.https.onRequest(
{cors: true},
(req, res) => {
const hours = (new Date().getHours() % 12) + 1;
res.status(200).send(`<!doctype html>
<head>
<title>Time</title>
</head>
<body>
${"BONG ".repeat(hours)}
</body>
</html>`);
});
这是我的 firebase.json
{
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log"
],
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
]
}
],
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
},
{
"source":"/bigben",
"function":{
"functionID":"bigben",
"region":"us-central1",
"pinTag":true
}
},
{
"source":"/helloworld",
"function":{
"functionID":"helloworld",
"region":"us-central1",
"pinTag":true
}
}
]
}
}
这是我的 firebase.js
import { initializeApp } from 'firebase/app';
import { getFunctions, httpsCallable } from 'firebase/functions';
const firebaseConfig = {
// I have put firebaseconfig here
apiKey: ,
authDomain:,
projectId: ,
storageBucket: ,
messagingSenderId: ,
appId:
};
const app = initializeApp(firebaseConfig);
const functions = getFunctions(app);
// Update the callFunction to use the Firebase Hosting URL
export const callFunction = () => {
return fetch('/bigben').then(response => response.json());
};
这是我在前端代码中调用函数的位置
import React, { useState, useEffect } from 'react';
import { callFunction } from '../firebase';
import './Home.css';
function Home() {
const [message, setMessage] = useState('Loading...');
useEffect(() => {
callFunction()
.then((response) => {
setMessage(response.data);
})
.catch((error) => {
console.error(error);
setMessage('Error fetching message');
});
}, []);
return (
<div className="Home">
<p className="hello-message">{message}</p>
<h1 className="Home-title">Grow Smarter, Grow Happier</h1>
<div className="About" >
<h2 className="About-title">Unlocking Nature's Secrets with AI</h2>
<p className="About-text">
Whether you're a seasoned farmer or nurturing your first seedling, we're here to help you cultivate success. Our app bridges the gap between cutting-edge technology and everyday gardening, empowering you to make informed decisions and achieve bountiful yields.
</p>
<div className="Features">
<h3 className="Features-title">Your Green Thumb's Best Friend</h3>
</div>
</div>
</div>
);
}
export default Home;
我已经看过这两个https://firebase.google.com/docs/functions/http-events?gen=2nd#node.js 和https://firebase.google.com/docs/hosting/functions 我尝试过以不同的方式包含 cors 最初我用 python 编写了 firebase 函数,但我无法让 cors 工作,所以我转向了 javascript 函数,但我仍然无法让它工作。
我是初学者,所以感谢任何帮助
当我在本地拥有网站前端时,我可以通过使用类似这样的东西与express作为中间件来使其工作
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
app.all('/predict', (req, res) => {
req.pipe(request.post('https://us-central1-diseasedet.cloudfunctions.net/predict')).pipe(res);
});
app.listen(5000, () => {
console.log('Proxy server listening on port 5000');
});
我在开始新项目时经常遇到这个问题。对我来说解决这个问题的方法是通过 firebase 网站删除功能,然后重新部署它。