上個月開始學習了解node.js,在學習的過程中邊學邊改造之前做過的課程設計,下面做下筆記。
搭建基於express框架的運行環境
- 安裝express generator生成器
cnpm i -g express-generator
- 通過生成器自動創建項目
express server
- 切換到server目錄下
cd server
- 下載依賴
cnpm i
- 跑起項目
cnpm run start
- 打開瀏覽器輸入訪問 127.0.0.1:3000
- 至此,就可以開始寫接口了
編寫接口
- 在server目錄下新建一個文件夾models,並在models文件夾下新建 notices. js
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);
- 在 app.js 中引用該模塊,添加下面兩句
var noticesRouter = require('./routes/notices'); app.use('/notices', noticesRouter);
- 在routes 目錄下新建一個 notices.js 文件,開始相關接口的編寫
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;
- 前端用的是vue,跨域處理暫時采用代理的方式,在項目文件夾下的 config 文件夾下的 index.js 中的 proxyTable 里面 增加 '/': { target: 'http://localhost:3000' } ,如下所示
proxyTable: { '/': { target: 'http://localhost:3000' } },
- 測試請求結果
- 前端接口請求結果
- 頁面展示