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依賴,
cnpm install express joi
對應的代碼如下:
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.