首页 > 解决方案 > Express 路由器删除和 Firebase Cloud Function 给出 TypeError: Cannot read property 'apply' of undefined

问题描述

我有一个带有 firebase.json 配置的 Firebase Cloud 功能:

{
    "hosting":
    {
        "public": "public",
        "ignore": [
            "firebase.json",
            "**/.*",
            "**/node_modules/**"
        ],
        "rewrites": [
        {
            "source": "**",
            "function": "api"
        },
        {
            "source": "/*",
            "function": "api"
        }]
    }
}

我的灵感来自:本教程本教程

路由器.js

const express = require('express');
const router = express.Router();
const cors = require('cors')
const firebaseHandler = require('../db/firebaseHandler')
router.use(cors())

router.delete('/:id', async (req, res, next) => {
    try {
        const id = req.params.id;
        if (!id) throw new Error('id is blank');
        await firebaseHandler.delete('worklogs', id);
        res.json({
            id
        });
    } catch(e) {
        next(e);
    }
});
module.exports = router;

firebaseHandler.js

const firebase = require('firebase');
const conf = require('../../../conf.json')

const config = {
    apiKey: conf.firebaseConfig.apiKey,
    authDomain: conf.firebaseConfig.authDomain,
    databaseURL: conf.firebaseConfig.databaseURL,
    projectId: conf.firebaseConfig.projectId,
    schemaPath: conf.schemaPath
};

firebaseApp = firebase.initializeApp(config);

const db = firebaseApp.firestore();

exports.delete = async (type, id) => {
    await database.collection(type).doc(id).delete(); 
}

在 url 中运行它时出现错误:http://localhost:5000/mycloudfunctionhere/api/documentidhere/

这是错误的堆栈跟踪:

projectpath\node_modules\express\lib\router\index.js:635
    return fn.apply(this, arguments);

TypeError: Cannot read property 'apply' of undefined
      at Immediate.<anonymous> (projectpath\node_modules\express\lib\router\index.js:635:15)
      at runCallback (timers.js:706:11)
      at tryOnImmediate (timers.js:676:5)
      at processImmediate (timers.js:658:5)

没有什么特别的,我已经尝试了多个示例,但我不断收到此错误..

提前致谢!

标签: node.jsfirebaseexpressgoogle-cloud-functionsexpress-router

解决方案


答案在于您不知道您不能在浏览器 url 中发出删除请求。只要我做了一个 curl -x DELETE http://localhost:5000/mycloudfunctionhere/api/documentidhere/,它就起作用了

谢谢大家的回答!


推荐阅读