上个月开始在慕课网上学习node.js,在学习的过程中边学边改造之前做过的课程设计,下面做下笔记。
搭建基于express框架的运行环境
cnpm i -g express-generator
express server
cd server
cnpm i
cnpm run start
编写接口
let mongoose = require(‘mongoose‘); let Schema = mongoose.Schema; let noticeSchema = new Schema({ "noticeId": String, "noticeTitle": String, "noticeContent": String, "adminId": Number, "adminName": String }); module.exports = mongoose.model(‘Notice‘,noticeSchema);
var noticesRouter = require(‘./routes/notices‘); app.use(‘/notices‘, noticesRouter);
let express = require(‘express‘); let router = express.Router(); let mongoose = require(‘mongoose‘); let Notices = require(‘../models/notices‘); //连接MongoDB数据库 mongoose.connect(‘mongodb://127.0.0.1:27017/park‘,{ useNewUrlParser: true }); // mongoose.connect(‘mongodb://root:123456@127.0.0.1:27017/park‘); mongoose.connection.on(‘connected‘, function() { console.log(‘MongoDB connected success.‘); }); mongoose.connection.on(‘error‘, function() { console.log(‘MongoDB connected fail.‘); }); mongoose.connection.on(‘disconnected‘, function() { console.log(‘MongoDB connected disconnected.‘); }); router.get("/", function(req, res, next) { // res.send(‘Hello, notices list.‘); Notices.find({}, function (err, doc) { if(err) { res.json({ status: ‘1‘, msg: err.message }); } else { res.json({ status:‘0‘, msg: ‘‘, result: { count: doc.length, list: doc } }) } }); }); module.exports = router;
原文:https://www.cnblogs.com/let423/p/9738651.html