mongoose Route.post()需要一个回调函数,但得到了一个[object Undefined](尽管我已经给出了回调函数)

xqnpmsa8  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(155)

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


这是错误

提前致谢。

2skhul33

2skhul331#

导致此问题的原因是您将 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`)});

wb1gzix0

wb1gzix02#

我只是犯了个小错误。
我在做这个。

module.exports = { router }

字符串
而不是

module.exports = router

3pvhb19x

3pvhb19x3#

对于我来说,我导入我的中间件,

const { default: fetchuser } = require("../middleware/fetchuser");

字符串
我需要输入

const fetchuser = require("../middleware/fetchuser");


而我出口的是

module.exports = { router }


而不是

module.exports = router;

结论:您应该正确导入和导出

相关问题