RESTful服务
REST(Representational State Transfer)的意思是表征状态转移,它是一种基于HTTP协议的网络应用接口风格,充分利用HTTP的方法实现统一风格接口的服务。通过动词(HTTP方法)+名词(请求资源的接口路径)的方式请求资源,赋予接口特定的含义。
REST风格定义了一系列创建HTTP服务的惯例:
- POST:创建资源
- PUT:更新资源
- GET:读取资源
- DELETE:删除资源
例如:
- 获取所有书籍: GET /api/books
- 获取id为1的书籍: GET /api/books/1
- 更新id为1的书籍:PUT /api/books/1
- 删除id为1的书籍:DELETE /api/books/1
- 添加书籍:POST /api/books
Express构建RESTful API
Express.js是一个轻量且灵活的Node.js WEB应用框架,可以快速搭建WEB应用。其底层是对Node.js的HTTP模块进行封装,增加路由、中间件等特性,使得用户能搭建应用级别的WEB服务。
处理GET请求
直接上代码:
const express = require('express');
const app = express();
const Joi = require('joi');
app.use(express.json());
const books = [
{ id: 1, name: 'book1'},
{ id: 2, name: 'book2'},
{ id: 3, name: 'book3'},
];
app.get('/', (req, res) => {
res.end('Hello World!');
});
//获取所有书籍
app.get('/api/books', (req, res) => {
res.json(books).end();
});
//获取特定id的书籍
app.get('/api/books/:id', (req, res) => {
let book = books.find(b => b.id === parseInt(req.params.id));
if(!book) return res.status(404).json({msg: 'The book with the given ID not find.'});
res.json(book).end();
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
GET /api/books
GET /api/books/2
GET /api/books/5
处理POST请求
function validateBook(book){
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(book, schema);
}
//使用POST方法添加书籍
app.post('/api/books', (req, res) => {
const {error} = validateBook(req.body);
if(error){
return res.status(400).json({msg: error.details[0].message}).end();
}
const book = {
id: books.length + 1,
name: req.body.name
};
books.push(book);
res.json(book).end();
});
POST /api/books
处理PUT请求
//使用PUT方法修改书籍
app.put('/api/books/:id', (req, res) => {
let book = books.find(b => b.id === parseInt(req.params.id));
if(!book) return res.status(404).json({msg: 'The book with the given ID not find.'});
const { error } = validateBook(req.body);
if(error) return res.status(400).json({msg: error.details[0].message}).end();
book.name = req.body.name;
res.json(book).end();
});
PUT /api/books/1
处理DELETE
//使用DELETE方法删除书籍
app.delete('/api/books/:id', (req, res) => {
let book = books.find(b => b.id === parseInt(req.params.id));
if(!book) return res.status(404).json({msg: 'The book with the given ID not find.'});
const index = books.indexOf(book);
books.splice(index, 1);
res.json(book).end();
});
DELETE /api/books/1