我正在创建一个 react 应用程序。我有这样的代码
async componentDidMount() {
const questions = await axios.get('getQuestions');
console.log(questions);
}
(我为 axios 等设置了基本 URL,因此 URL 是正确的)
我创建了一个 firebase 函数,如下( typescript )
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
const db = admin.firestore();
exports.getQuestions = functions.https.onRequest(async (request, response) => {
const questions = [];
const querySnapshot = await db.collection('questions').get();
const documents = querySnapshot.docs;
documents.forEach(doc => {
questions.push(doc.data());
});
response.json({ questions: questions });
});
现在,当我构建并运行 firebase deploy --only 函数,然后直接访问 url 时,一切正常。我看到了我的问题。
但是在 react 应用程序中,我收到以下错误
Access to XMLHttpRequest at '.../getQuestions' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
经过一番谷歌搜索后,我尝试了
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
const db = admin.firestore();
const cors = require('cors')({ origin: true });
exports.getQuestions = functions.https.onRequest(
cors(async (request, response) => {
const questions = [];
const querySnapshot = await db.collection('questions').get();
const documents = querySnapshot.docs;
documents.forEach(doc => {
questions.push(doc.data());
});
response.json({ questions: questions });
})
);
但是当我运行 firebase deploy --only 函数时,这给了我一个错误
✔ functions: Finished running predeploy script. i functions: ensuring necessary APIs are enabled... ✔ functions: all necessary APIs are enabled i functions: preparing functions directory for uploading...
Error: Error occurred while parsing your function triggers.
TypeError: Cannot read property 'origin' of undefined at ...
而且,即使这个命令有效,我也不知道这是否是正确的解决方案
最佳答案
明白了:)我做了一些愚蠢的事情
import * as cors from 'cors';
const corsHandler = cors({ origin: true });
exports.getQuestions = functions.https.onRequest(async (request, response) => {
corsHandler(request, response, async () => {
const questions = [];
const querySnapshot = await db.collection('questions').get();
const documents = querySnapshot.docs;
documents.forEach(doc => {
questions.push(doc.data());
});
response.status(200).json({ questions: questions });
});
});
关于firebase - 尝试从 React 应用程序连接到 firebase 函数 - 有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997577/