利用express搭建一個restful api 服務器


學習express有幾天了,記錄一下內容也給入門的兄弟們一點提示。

想要解決的問題:

  1. node開發過程中自動重啟服務器,無需每次都要運行node index.js啟動服務器(nodemon)
  2. 使用ES6,ES7 編寫代碼,自動編譯 使用import,export新特性。(babel)
  3. 使用express開發RESTFUL API,模塊化開發。
  4. 學習postman中的提交內容方式。
  5. 利用mongoose中間件來實現model層映射。
  6. 利用body-parser中間件來實現提交內容解析。(multipart/form-data數據類型不支持,此種提交多用於form帶file類型提交

1. 開發環境

  nodejs@v10.2.0

  npm@5.6.0

  windows 10

  portableGit

2. 搭建開發目錄結構 (代碼地址https://github.com/jingyinggong/expressjs_app1.git

  2.1 啟動portableGit

  2.2 cd /d/

  2.3 mkdir web

  2.4 在web目錄下創建src目錄和dist目錄, 並創建相應文件

  目錄結構如下:

  |-- dist

  |-- .babelrc
  |-- package.json

  |-- postman.json
  `-- src
    |-- index.js
    |-- models
    |    `-- user.js
    `-- routes
      |-- index.js
      `-- user.js

  2.5 在web目錄下運行npm install

3. 填充目錄文件內容

  3.1 package.json

//package.json
{
  "name": "app2",
  "version": "1.0.0",
  "description": "test for babel",
  "main": "dist/index.js",
  "scripts": {
    "watch": "babel -w src/ -d dist/",
    "build": "babel src/ -d dist/",
    "serve": "babel -w src/ -d dist/ | nodemon --watch dist",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "LoganGong",
  "license": "MIT",
  "devDependencies": {
    "express": "latest",
    "mongoose": "latest",
    "lodash": "latest",
    "eslint": "latest",
    "body-parser": "latest",
    "babel": "^6.23.0",
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-0": "^6.24.1",
    "nodemon": "^1.17.5"
  }
}

  3.2 .babelrc

{
    "presets": ["env", "stage-0"]
}

  3.3 src/index.js

import Routes from './routes';
import mongoose from 'mongoose';

import express from 'express'; // call express
var app = express(); // define our app using express

mongoose.connect('mongodb://localhost:27017/chat');

var port = process.env.PORT || 8080; // set our port

var router = express.Router(); // get an instance of the express Router

router.use(function(req, res, next) {
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});
app.use('/api', Routes);

  3.4 src/routes/index.js

import { Router } from 'express';
import User from'./user';

const router = Router();

router.use('/users', User);

exports = module.exports = router;

  3.5 src/routes/user.js

import { Router } from 'express';

import User from '../models/user';

var bodyParser = require('body-parser');

const router = Router();

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.raw());

router.route('/').get((req, res) => {
    User.find(function (err, users) {
        if (err) res.send(err);
        res.json(users);
    });
}).post((req, res) => {
    var user = new User(); // create a new instance of the Bear model
    user.name = req.body.name; // set the bears name (comes from the request)
    user.nickname = req.body.nickname;
    user.gender = req.body.gender;
    user.password = req.body.password;
    user.role = req.body.role;
    user.createdTime = new Date().getTime();
    // save the bear and check for errors
    user.save(function (err) {
        if (err) res.send(err);
        console.log(user);
        res.json(user);
    });
}).patch((req, res) => {
    console.log(req.body);
    User.updateMany({ gender: req.body.gender }, {nickname: req.body.nickname}, function (err, users) {
        if (err) res.send(err);
        res.json(users);
    });
});

router.route('/:uid').get((req, res) => {
    User.findById(req.params.uid, function (err, user) {
        if (err) res.send(err);
        res.json(user);
    });
}).delete((req, res) => {
    console.log(req.params.uid)
    User.deleteOne({ _id: req.params.uid }, function (err, user) {
        if (err) res.send(err);
        console.log({"msg": req.params.uid + ' is deleted'});
        User.find(function (err, users) {
            if (err) res.send(err);
            res.json(users);
        });
    });
});

export default router;

  3.7 src/models/user.js

import mongoose from 'mongoose';

//console.log(mongoose);

var Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: String,
    nickname: String,
    gender: Number,
    password: String,
    createdTime: { type: Date, default: Date.now },
    role: Number  //1: admin 2: group owner, 3: normal user
});

export default mongoose.model('User', UserSchema);

  3.7 postman.json

{
    "info": {
        "_postman_id": "5d769b8a-47b5-4242-92cf-fef3523bcda4",
        "name": "express_app1_restful_api",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
        {
            "name": "get user item",
            "request": {
                "method": "GET",
                "header": [
                    {
                        "key": "Content-Type",
                        "value": "application/x-www-form-urlencoded"
                    }
                ],
                "body": {
                    "mode": "urlencoded",
                    "urlencoded": [
                        {
                            "key": "name",
                            "value": "BearKing",
                            "description": "",
                            "type": "text"
                        }
                    ]
                },
                "url": {
                    "raw": "http://localhost:8080/api/users/5b12581a3cb88b2eacb45b1c",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "8080",
                    "path": [
                        "api",
                        "users",
                        "5b12581a3cb88b2eacb45b1c"
                    ]
                }
            },
            "response": []
        },
        {
            "name": "delete user item",
            "request": {
                "method": "DELETE",
                "header": [
                    {
                        "key": "Content-Type",
                        "value": "application/x-www-form-urlencoded"
                    }
                ],
                "body": {
                    "mode": "urlencoded",
                    "urlencoded": [
                        {
                            "key": "name",
                            "value": "BearKing",
                            "description": "",
                            "type": "text"
                        }
                    ]
                },
                "url": {
                    "raw": "http://localhost:8080/api/users/5b125ce2f0196b1b8097ea44",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "8080",
                    "path": [
                        "api",
                        "users",
                        "5b125ce2f0196b1b8097ea44"
                    ]
                }
            },
            "response": []
        },
        {
            "name": "add a user",
            "request": {
                "method": "POST",
                "header": [
                    {
                        "key": "Content-Type",
                        "value": "application/x-www-form-urlencoded"
                    }
                ],
                "body": {
                    "mode": "urlencoded",
                    "urlencoded": [
                        {
                            "key": "name",
                            "value": "張三2",
                            "type": "text",
                            "description": ""
                        },
                        {
                            "key": "nickname",
                            "value": "張三2",
                            "type": "text",
                            "description": ""
                        },
                        {
                            "key": "gender",
                            "value": "3",
                            "type": "text",
                            "description": ""
                        },
                        {
                            "key": "password",
                            "value": "1233",
                            "type": "text",
                            "description": ""
                        },
                        {
                            "key": "role",
                            "value": "22",
                            "type": "text",
                            "description": ""
                        }
                    ]
                },
                "url": {
                    "raw": "http://localhost:8080/api/users",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "8080",
                    "path": [
                        "api",
                        "users"
                    ]
                }
            },
            "response": []
        },
        {
            "name": "get user list",
            "request": {
                "method": "GET",
                "header": [
                    {
                        "key": "Content-Type",
                        "value": "application/x-www-form-urlencoded"
                    }
                ],
                "body": {
                    "mode": "urlencoded",
                    "urlencoded": [
                        {
                            "key": "name",
                            "value": "BearKing",
                            "description": "",
                            "type": "text"
                        }
                    ]
                },
                "url": {
                    "raw": "http://localhost:8080/api/users/",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "8080",
                    "path": [
                        "api",
                        "users",
                        ""
                    ]
                }
            },
            "response": []
        },
        {
            "name": "update user list",
            "request": {
                "method": "PATCH",
                "header": [
                    {
                        "key": "Content-Type",
                        "value": "application/x-www-form-urlencoded"
                    }
                ],
                "body": {
                    "mode": "urlencoded",
                    "urlencoded": [
                        {
                            "key": "gender",
                            "value": "1",
                            "description": "",
                            "type": "text"
                        },
                        {
                            "key": "nickname",
                            "value": "shoott",
                            "description": "",
                            "type": "text"
                        }
                    ]
                },
                "url": {
                    "raw": "http://localhost:8080/api/users/",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "8080",
                    "path": [
                        "api",
                        "users",
                        ""
                    ]
                }
            },
            "response": []
        }
    ]
}

 

基本完成 express代碼開發。

4. 安裝mongodb

5. 啟動mongodb

7. web目錄下運行“npm run serve" 啟動server

8. 運行postman

9. 文件-導入-選擇web目錄下的postman.json

10. 各種添加和列表測試就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM