Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh
在Youtube上看到Mosh的一篇关于使用Node和Express构建RESTful APIs的示例,对应的视频地址是:Express.js Tutorial: Build RESTful APIs with Node and Express | Mosh,作者Mosh的Youtube地址是:Programming with Mosh
TABLE OF CONTENT:
00:49 What are RESTful APIs 06:48 Introducing Express 09:09 Your First Web Server 14:57 Nodemon 16:29 Environment Variables 19:44 Route Parameters 25:22 Handling HTTP GET Requests 30:09 Handling HTTP POST Requests 33:53 Calling APIs using Postman 36:03 Input Validation 44:03 Handling HTTP PUT Requests 52:33 Handling HTTP DELETE Requests
http://programmingwithmosh.com
创建程序
首先保证在自己的系统下安装了Node.js程序,然后安装配置node和npm、cnpm等 然后使用cnpm或npm安装express和joi依赖,
代码语言:javascript复制cnpm install express joi
对应的代码如下:
代码语言:javascript复制const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());
// 课程列表数组
const courses =[
{ id: 1, name: '语文' },
{ id: 2, name: '数学' },
{ id: 3, name: '英语' },
{ id: 4, name: '计算机组成原理' },
{ id: 5, name: '数据结构' },
{ id: 6, name: '操作系统' },
{ id: 7, name: '编译原理' }
]
app.get('/', (req, res) => {
res.send('Hello World');
})
// 获取所有的课程信息
app.get('/api/courses', (req, res) => {
res.send(courses);
});
// 提交一门课程
app.post('/api/courses', (req, res) => {
const { error } = validateCourse(req.body); // result.error
if (error) {
return res.status(400).send(error.details[0].message);
}
// 在提交课程前,对课程名进行校验,若课程名为空或者小于3个字符,则返回
// if (!req.body.name || req.body.name.length < 3) {
// // 400 Bad Request
// res.status(400).send('Name is required and should be minimum 3 characters.');
// return;
// }
// 创建一个课程对象
const course = {
id: courses.length 1,
name: req.body.name
};
// 向课程列表数组中添加一个新项
courses.push(course);
res.send(course);
});
// 根据课程id查询某个课程
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) { // 404
return res.status(404).send('The course with the given ID was not found!');
}
res.send(course);
});
// 根据课程id更新某门课程
app.put('/api/courses/:id', (req, res) => {
// Look up the course
// If not existing, return 404
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) { // 404
return res.status(404).send('The course with the given ID was not found!');
}
// Validate
// If invalid, return 400 - Bad request
const { error } = validateCourse(req.body); // result.error
if (error) {
return res.status(400).send(error.details[0].message);
}
// Update course
// Return the updated course
course.name = req.body.name;
res.send(course);
});
// 根据课程id删除某门课程
app.delete('/api/courses/:id', (req, res) => {
// Look up the course
// Not existing, return 404
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) { // 404
return res.status(404).send('The course with the given ID was not found!');
}
// Delete
const index = courses.indexOf(course);
courses.splice(index, 1);
// Return the same course
res.send(course);
})
// app.get('/api/posts/:year/:month', (req, res) => {
// res.send(req.params);
// //res.send(req.query);
// });
// app.post()
// app.put()
// app.delete()
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App Listening on port ${port}...`);
});
function validateCourse(course) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(course, schema);
}
关于http接口测试工具,可以使用Postman或者在VSCode中使用rest-client插件进行测试,或者使用curl工具进行测试。
不过需要注意的是,在npm官网上作者说joi包已经被废弃了,建议使用@hapi/joi
This package has been deprecated Author message:
This module has moved and is now available at @hapi/joi. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
参考资料
- joi
- https://hapi.dev/module/joi/
- @hapi/joi
- jjoi-The most powerful data validation library for JS