I am creating a backend app using Express JS. But while testing the code on live server, I am getting error: Cannot read property 'Router' of undefined. Here is my code:
Server.js
var Todo = require('./models/Todo');
var router = express.Router();
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose');
router.route('/create').post((req, res) => {
var todo = new Todo(req.body);
todo.save().then( todo => {
res.status(200).json({'message': 'Todo successfully added '});
})
.catch(err => {
res.status(400).send("Error when saving to database");
});
});
router.route('/todos').get((req, res) => {
Todo.find((err, todos) =>{
if(err){
console.log(err);
}
else {
res.json(todos);
}
});
});
router.route('/todos/:id').get((req, res) => {
var id = req.params.id;
Todo.findById(id, (err, todo) =>{
res.json(todo);
});
});
router.route('/todos/:id').put((req, res) => {
Todo.findById(req.params.id, (err, todo) => {
if (!todo)
return next(new Error('Error getting the todo!'));
else {
todo.name = req.body.name;
todo.save().then( todo => {
res.json('Todo updated successfully');
})
.catch(err => {
res.status(400).send("Error when updating the todo");
});
}
});
});
router.route('/todos/:id').get((req, res) => {
Todo.findByIdAndRemove({_id: req.params.id}, (err,todo) =>{
if(err) res.json(err);
else res.json('Todo successfully removed');
});
});
mongoose.connect("mongodb://localhost:27017/vuenodedb").then(
() => {console.log('Database connection is successful') },
err => { console.log('Error when connecting to the database'+ err)}
);
.........
I am referring this link for the tutorial purpose: https://www.techiediaries.com/vue-js-express-tutorial/
You are trying to access express before initializing it. Here is your code:
var router = express.Router();
var express = require('express');
Initialize express first then use Router
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.