Route.post() 需要一个回调函数但是得到了一个 [object Undefined] (即使我已经给了回调函数)

Route.post() requires a callback function but got a [object Undefined] (even though I have given the callback function)

我正在创建一个简单的博客后端 (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)

这是错误

提前致谢。

出现此问题是因为您将 article.js 导入 app.js,然后导入 app.jsarticle.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`)});

我犯了一个简单的错误。

我正在做这个。

module.exports = { router }

而不是

module.exports = router