学习restful api

203 阅读1分钟
原文链接: zhuanlan.zhihu.com
了解RESTful API

推荐阅读:

https://github.com/aisuhua/restful-api-design-referencesgithub.com


Node实现的简易版本




// bear.js

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true })
const Schema = mongoose.Schema

const BearSchema = new Schema({
	name: String
})

module.exports = mongoose.model('Bear', BearSchema)



// package.json

{
  "name": "restful-api-node",
  "version": "1.0.0",
  "description": "node api restful",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "keywords": [
    "node",
    "restful",
    "api"
  ],
  "author": "xyz",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "mongoose": "^5.3.13"
  },
  "devDependencies": {
    "nodemon": "^1.18.6"
  }
}


// server.js

const Express = require('express')
const Bear = require('./app/models/bear.js')
const app = Express()
// 路由实例
const router = Express.Router()
const PORT = process.env.port || 3000

app.use(Express.json())
app.use(Express.urlencoded({extended: false}))
app.use(function (req, res, next) {
	console.log('开始请求...')
	next()
})

router.route('/bears')
	.post(function (req, res) {
		const name = req.body.name
		if (!name) {
			res.json({
				message: '参数name不能为空',
			})
		}
		const bear = new Bear({
			name
		})
		bear.save(function (err, bear) {
			if (err) {
				res.send(err)
			}
			res.json({
				message: '创建成功'
			})
		})
	})
	.get(function (req, res) {
		Bear.find(function (err, bears) {
			if (err) {
				res.send(err)
			}
			res.json({
				bears
			})
		})
	})

router.route('/bears/:bear_id')
	.get(function (req, res) {
		const bear_id = req.params.bear_id
		Bear.findById(bear_id, function (err, bear) {
			if (err) {
				res.send(err)
			}
			res.json(bear)
		})
	})
	.put(function (req, res) {
		const name = req.body.name
		if (!name) {
			res.json({
				message: '参数name不能为空'
			})
		}
		const bear_id = req.params.bear_id
		Bear.findById(bear_id, function (err, bear) {
			if (err) {
				res.send(err)
			}
			bear.name = name
			bear.save(function (err, bear) {
				if (err) {
					res.send(err)
				}
				res.json({
					message: '更新成功'
				})	
			})
		})
	})
	.delete(function (req, res) {
		const bear_id = req.params.bear_id
		Bear.remove({_id: bear_id}, function (err) {
			if (err) {
				res.send(err)
			}
			res.json({
				message: '删除成功'
			})
		})
	})

// 路由中间件
router.get('/', function (req, res, next) {
	res.json({
		msg: '进入restful api'
	})
})

app.use('/api', router)
app.listen(PORT)
console.log(`server is on the port: ${PORT}`)