如何在Node JS中使用Express创建控制器和路由器

时间:2019-06-02 11:10:33

标签: node.js express

我正在使用节点JS设置新服务器。如何创建控制器和路由器。

这是我的新服务器。运行mongo DB

5 个答案:

答案 0 :(得分:0)

app.js

var Express     = require('Express');
var bodyParser  = require('body-parser');
var Cors        = require('cors');
var router      = Express.Router();
var UserRoute   = require('./User/user.route');

var app = Express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(Cors());
app.use('/', UserRoute);

app.listen('8081', '127.0.0.1', function(err) {
    if(err) {
        console.log(err);
        process.exit(-1);
    }
    console.log("Server listen on port 8081");
})

mongoose.config.js

const mongoose  = require('mongoose');
const Schema    = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String,
        require: true
    }
});

mongoose.model('User', UserSchema);

mongoose.connect('mongodb://localhost:27017/user_demo', (err) => {
    if (err) {
        console.log(err);
        process.exit(-1);
    }
    console.log('Connected to the DB');
});

module.exports = mongoose;

答案 1 :(得分:0)

const express = require('express');
const router = express.Router();

//Course Model
const Course = require('../models/Course');

//@route GET /courses
//Gets all courses
//@access Public
router.get('/get-courses', (req,res) => {
    Course.find()
        .then(courses =>res.json(courses))
});


//@route GET /course
//Gets a particular course
//@access Public
router.get('/get-course/:id', (req,res) => {
    Course.findById(req.params.id)
        .then(course => res.json(course));
});

//Gets subjects in a given course
router.get('/:id/subjects', (req,res) =>{
    Course.findById(req.params.id)
        .populate('subjects')
        .select('name')
        .then(subjects => res.json(subjects));

});

//@route POST /courses
//Adds a new course
//@access Public
router.post('/add-course', (req,res) => {
    const newCourse = new Course({
        name: req.body.name,
        code:req.body.code,
        passMark: req.body.passMark,
        lecturerInCharge: req.body.lecturerInCharge,
        subjects: req.body.subjects
    });
    newCourse.save()
        .then(course => res.json(course));
});


//@route DELETE /courses
//Deletes a course
//@access Public
router.delete('/delete-course/:id', (req,res) => {
    Course.findById(req.params.id)
        .then(course => course.remove() . then(() => res.json({success:true})))
        .catch(err => res.status(404).json({success:false}));
});

module.exports= router;

答案 2 :(得分:0)

//I think by using this we can avoid creating two classes, like controller and router

const express = require('express');
const router = express.Router();

//Course Model
const Course = require('../models/Course');

//@route GET /courses
//Gets all courses
//@access Public
router.get('/get-courses', (req,res) => {
    Course.find()
        .then(courses =>res.json(courses))
});


//@route GET /course
//Gets a particular course
//@access Public
router.get('/get-course/:id', (req,res) => {
    Course.findById(req.params.id)
        .then(course => res.json(course));
});

//Gets subjects in a given course
router.get('/:id/subjects', (req,res) =>{
    Course.findById(req.params.id)
        .populate('subjects')
        .select('name')
        .then(subjects => res.json(subjects));

});

//@route POST /courses
//Adds a new course
//@access Public
router.post('/add-course', (req,res) => {
    const newCourse = new Course({
        name: req.body.name,
        code:req.body.code,
        passMark: req.body.passMark,
        lecturerInCharge: req.body.lecturerInCharge,
        subjects: req.body.subjects
    });
    newCourse.save()
        .then(course => res.json(course));
});


//@route DELETE /courses
//Deletes a course
//@access Public
router.delete('/delete-course/:id', (req,res) => {
    Course.findById(req.params.id)
        .then(course => course.remove() . then(() => res.json({success:true})))
        .catch(err => res.status(404).json({success:false}));
});

module.exports= router;

答案 3 :(得分:-1)

user.controller.js

var mongoose    = require('../mongoose.config');
var UserSchema  = mongoose.model('User');
var UserController = function() {

    this.add = function(userInstance) {
        return new Promise((resolve, reject) => {
            var user = new UserSchema({
                name: userInstance.name
            })
            user.save().then(() => {
                resolve({'status': 200, 'message':'added new user'});
            }).catch(err => {
                reject({'status': 404, 'message':'err:-'+err});
            })
        })
    }

    this.getAll = function() {
        return new Promise((resolve, reject) => {
            UserSchema.find().exec().then(data => {
                resolve({'status': 200, 'message':'get all data', 'data': data});
            }).catch(err => {
                reject({'status': 404, 'message':'err:-'+err});
            })
        })
    }

    this.getSingle = function(id) {
        return new Promise((resolve, reject) => {
            UserSchema.find({_id: id}).exec().then(data => {
                resolve({'status': 200, 'message':'get single data', 'data': data});
            }).catch(err => {
                reject({'status': 404, 'message':'err:-'+err});
            })
        })
    }

    this.update = function(id, updateData) {
        return new Promise((resolve, reject) => {
            UserSchema.update({_id: id}, updateData).then(() => {
                resolve({'status': 200, 'message':'update user'});
            }).catch(err => {
                reject({'status': 404, 'message':'err:-'+err});
            })
        })
    }

    this.delete = function(id) {
        return new Promise((resolve, reject) => {
            UserSchema.remove({_id: id}).then(() => {
                resolve({'status': 200, 'message':'delete user'});
            }).catch(err => {
                reject({'status': 404, 'message':'err:-'+err});
            })
        })
    }

}

module.exports = new UserController();

答案 4 :(得分:-1)

Router

var express     = require('express');
var router      = express.Router();
var controller  = require('./user.controller');

router.post('/', (req, res) => {
    controller.add(req.body).then(response => {
        res.status(response.status).send(response.message);
    }).catch(err => {
        res.status(err.status).send(err.message);
    })
});

router.get('/', (req, res) => {
    controller.getAll().then(response => {
        res.status(response.status).send(response);
    }).catch(err => {
        res.status(err.status).send(err.message);
    })
});

router.get('/:id', (req, res) => {
    controller.getSingle(req.params.id).then(response => {
        res.status(response.status).send(response);
    }).catch(err => {
        res.status(err.status).send(err.message);
    })
});

router.put('/:id', (req, res) => {
    controller.update(req.params.id, req.body).then(response => {
        res.status(response.status).send(response);
    }).catch(err => {
        res.status(err.status).send(err.message);
    })
});

router.delete('/:id', (req, res) => {
    controller.delete(req.params.id).then(response => {
        res.status(response.status).send(response);
    }).catch(err => {
        res.status(err.status).send(err.message);
    })
})

module.exports = router;