首页 文章

调用Firebase功能时出错 . TypeError:无法在/user_code/node_modules/cors/lib/index.js:219:39读取未定义的属性'origin'

提问于
浏览
0

我编写了Firebase功能并将其部署到Firebase . 我采取的部署步骤是 -

  • 在我的本地项目根文件夹中,我运行"firebase init",后来创建了函数文件夹 .

  • cd函数 . 然后运行"npm install --save firebase-admin firebase-functions cors"

  • 修改了index.js以适合我自己的名为storePostData()的函数 .

  • 通过cd返回我的根文件夹..

  • 运行"firebase deploy"

  • 已验证该功能已在我的Firebase功能面板中上传和创建 .

index.js


const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true, });

exports.storePostData = functions.https.onRequest((request, response) => {
  return cors((request, response) => {

    admin.database().ref('posts').push({
      id: request.body.id,
      title: request.body.title,
      location: request.body.location,
      image: request.body.image
    })
      .then(() => {
        response.status(201).json({message: 'Data stored', id: request.body.id});
      })
      .catch((err) => {
        response.status(500).json({error: err});
      });

  });
});

我的问题是,每当我尝试调用我的firebase函数时,比如fetch('https://us-central1- .cloudfunctions.net / storePostData',mypost),我会点击错误说"TypeError: Cannot read property 'origin' of undefined at /user_code/node_modules/cors/lib/index.js:219:39" .

我在我的智慧结束,并广泛搜索,...,有没有人之前遇到此错误并设法解决它?

rgds,新手

1 回答

  • 0

    您应该首先使用 firebase serve --only functions 测试您的功能 . 另外我看到你没有使用 admin.initializeApp() 初始化firebase

相关问题