利用express搭建一个restful api 服务器
Posted jingyingggong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用express搭建一个restful api 服务器相关的知识,希望对你有一定的参考价值。
学习express有几天了,记录一下内容也给入门的兄弟们一点提示。
想要解决的问题:
- node开发过程中自动重启服务器,无需每次都要运行node index.js启动服务器(nodemon)
- 使用ES6,ES7 编写代码,自动编译 使用import,export新特性。(babel)
- 使用express开发RESTFUL API,模块化开发。
- 学习postman中的提交内容方式。
- 利用mongoose中间件来实现model层映射。
- 利用body-parser中间件来实现提交内容解析。(multipart/form-data数据类型不支持,此种提交多用于form带file类型提交)
1. 开发环境
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. 各种添加和列表测试就可以了。
以上是关于利用express搭建一个restful api 服务器的主要内容,如果未能解决你的问题,请参考以下文章
NodeJs+Express+SqlServer简易后台API服务搭建