【问题标题】:Route.post() requires a callback function but got a [object Undefined] (even though I have given the callback function)Route.post() 需要一个回调函数,但得到了一个 [object Undefined](即使我已经给出了回调函数)
【发布时间】:2021-10-01 15:18:11
【问题描述】:

我正在创建一个简单的博客后端 (API)。

我尝试创建一个路由器,但现在我遇到了一个我不明白如何调试的问题。

这是路由器。

const express = require('express');
const Article = require('../models/Article')
let router = express.Router();
const app = require('../app');


router.get('/:articleId', (req,res) => {
    Post.findOne({_id : req.params.articleId})
    .then(doc => {
        if(!doc) res.send('No such post in DB')
        res.send(doc).sendStatus(200)
    })
    .catch(err => res.send({'error' : `you got some error - ${err}`}).sendStatus(400))
})

router.post('/', app.auth, async (req,res)=>{
    if(req.auth) {
        const doc = await User.findOne({uname : req.user});
        const article = {
            authorId : doc._id,
            article : {
                title : req.body.title,
                content : req.body.article
            },
            tags : req.body.tags
        }
        const newArticle = new Article(article)
        const savedArticle = await newArticle.save()
        res.send(savedArticle)
    }
    else {
        res.redirect('./login')
    }
    //if(localStorage.token) verify(token) get the userId and post the article with authorId = userId
    //if (not verified) redirect to the login page
    //get to know the jwt tokens
})

module.exports = { router };

这是索引文件app.js。只是有问题的部分。还有我正在导出的auth,并且在app.js 中运行良好。

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const env = require('dotenv').config();
const article = require('./routes/article')

app.use(express.json());
app.use(express.urlencoded({extended : true}));

mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology : true
}).then(() => {
    console.log("Successfully connected to the database");    
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...', err);
    process.exit();
})

app.use("/article", article)
module.exports = {auth}

app.listen(port, ()=>{console.log(`Server running at port ${port}`)});

这是文章的模型

const mongoose = require('mongoose');

const Article = new mongoose.Schema({
    authorId : {
        type : String,
        required :true,
        default : "anonymous"
    },
    article : {
        title : {
            type : String,
            required : true
        },
        content : {
            type : [String],
            required : true
        },
        imgFiles : [String]
    },
    like : Number,
    starred : Number,
    date : {
        type : Date,
        required : true,
        default : Date.now()
    },
    tags : [String]
})

module.exports = mongoose.model('Article', Article)

这就是错误

提前致谢。

【问题讨论】:

    标签: node.js express mongoose express-router


    【解决方案1】:

    问题是因为您将 article.js 导入到 app.js 然后将 app.js 导入到 article.js 创建循环依赖。从 app.js 中删除 module.exports = {auth}。请注意,您甚至还没有声明 auth 函数。您应该在另一个文件中创建 auth 函数并将其导入 article.js。

    这行module.exports = { router }; 应该只是module.exports = router;

    auth.js

    function auth(req, res, next) {
      // IMplementation
    }
    module.exports = auth
    

    article.js

    const express = require('express');
    let router = express.Router();
    const auth = require('./auth');
    
    
    router.get('/:articleId', (req,res) => {
        res.send('article')
    })
    
    router.post('/', auth, async (req,res)=>{
        res.send('response')
    })
    
    module.exports = router;
    

    app.js

    const express = require('express');
    const app = express();
    const article = require('./article')
    
    app.use(express.json());
    app.use(express.urlencoded({extended : true}));
    
    app.use("/article", article)
    
    app.listen(3000, ()=>{console.log(`Server running at port 3000`)});
    

    【讨论】:

    • 是的,我也曾经认为这是问题所在,但事实并非如此。我已将其移至另一个 config 文件并从那里将其导入到这两个文件中。但随后这个TypeError: Router.use() requires a middleware function but got a Object 被提出。每次我尝试做出一些我认为可能会解决问题以了解问题来自何处的更改时,都会引发另一个问题。除非我从app.js 中删除article.js 文件,否则总会出现错误。我注释掉了 article.post 请求,但随后出现了 Router.use() 的错误。请尝试查找其他问题
    【解决方案2】:

    我犯了一个简单的错误。

    我正在这样做。

    module.exports = { router }
    

    而不是

    module.exports = router
    

    【讨论】:

    • @D_M 在他的回答中已经说过了。怎么又写到这里了?
    • 这就是为什么我赞成他的回答,但他也在谈论相互依赖。想要排除它,因为它可能会在您的 API 中作为错误出现,但在语法上并没有错误。
    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多