利用node.js編寫後臺接口

上個月開始學習瞭解node.js,在學習的過程當中邊學邊改造以前作過的課程設計,下面作下筆記。前端

搭建基於express框架的運行環境vue

  • 安裝express generator生成器
    cnpm i -g express-generator

  • 經過生成器自動建立項目
    express server

  • 切換到server目錄下
    cd server

  • 下載依賴
    cnpm i

      

  • 跑起項目
    cnpm run start 

  • 打開瀏覽器輸入訪問 127.0.0.1:3000 
  • 至此,就能夠開始寫接口了

 

 

編寫接口node

  • 在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'
          }
    },

     

  • 測試請求結果

  • 前端接口請求結果

  • 頁面展現

相關文章
相關標籤/搜索