node.jsexpressmongooseexpress-router

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


I am creating a simple blog backend (API).

I tried creating a router and now I have an issue that I don't understand how to debug.

This is the router.

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 };

This is the index file app.js. Just the part with the issue. And there is auth which I am exporting and is working fine within the 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}`)});

And this is the Model for Article

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)

And this is the error enter image description here

Thanks in Advance.


Solution

  • The issue is being caused because you are importing article.js into app.js and then importing the app.js into article.js creating a circular dependency. Remove that module.exports = {auth} from app.js. Note that you haven't even declared the auth function. You you should create the auth function in another file and import it into article.js.

    Also this line module.exports = { router }; should just be 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`)});