Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

javascript - 无法读取expressJS中未定义的属性“ Router”?(Cannot read property 'Router' of undefined in expressJS?)

I am creating a backend app using Express JS.(我正在使用Express JS创建一个后端应用程序。)

But while testing the code on live server, I am getting error: Cannot read property 'Router' of undefined.(但是在实时服务器上测试代码时,出现错误:无法读取未定义的属性“ Router”。) Here is my code:(这是我的代码:) Server.js(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/(我将此链接用于教学目的: https : //www.techiediaries.com/vue-js-express-tutorial/)   ask by Hemant Singh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are trying to access express before initializing it.(您正在尝试初始化Express。)

Here is your code:(这是您的代码:) var router = express.Router(); var express = require('express'); Initialize express first then use Router .(首先初始化Express,然后使用Router 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...