RESTful
Representational State Transfer
Express
// index.js
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Helo Express')
})
app.listen(3000, () => {
console.log('Listening on port 3000...')
})
nodeMon
npm i -g nodemon
nodemon : 无法加载文件 C:\Users\cell\AppData\Roaming\npm\nodemon.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。
解决方案:
(1) 管理员身份运行PowerShell
(2)输入下面命令并回车
set-ExecutionPolicy RemoteSigned
(3)选择Y
(4)重新尝试
Handling HTTP GET Request
// index.js
const express = require('express')
const app = express()
const courses = [
{ id: 1, name: 'course1' },
{ id: 2, name: 'course2' },
{ id: 3, name: 'course3' },
]
app.get('/', (req, res) => {
res.send('Helo Express!')
})
app.get('/api/courses', (req, res) => {
res.send(courses)
})
app.get('/api/courses/:id', (req, res) => {
const id = req.params.id
const result = courses.find(c => c.id === parseInt(id))
if (!result) {
res.status(404).send('The course with the given ID was not found!')
} else {
res.send(result)
}
})
// PORT
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`Listening on port ${port}...`)
})
Handling HTTP POST Request
app.use(express.json())
// ...
app.post('/api/courses', (req, res) => {
const { name } = req.body
const course = {
id: courses.length + 1,
name
}
courses.push(course)
res.send(course)
})
使用Joi进行验证
const Joi = require('joi')
app.post('/api/courses', (req, res) => {
const scheam = {
name: Joi.string().required()
}
const result = Joi.validate(req.body, scheam)
if (result.error) {
res.status(400).send(result.error.details[0].message)
return
}
const course = {
id: courses.length + 1,
name: req.body.name
}
courses.push(course)
res.send(course)
})
Handling HTTP PUT Request
app.put('/api/courses/:id', (req, res) => {
// 查找当前课程
const id = req.params.id
const course = courses.find(c => c.id === parseInt(id))
if (!course) {
res.status(404).send('The course with the given ID was not found!')
return
}
// 验证参数
const { error } = validateCourse(req.body)
if (error) {
res.status(400).send(error.details[0].message)
return
}
// 更新课程
course.name = req.body.name
res.send(course)
})
function validateCourse(course) {
const scheam = {
name: Joi.string().required()
}
return Joi.validate(course, scheam)
}
Handling HTTP DELETE Request
app.delete('/api/courses/:id', (req, res) => {
// 查找课程
const id = req.params.id
const course = courses.find(c => c.id === parseInt(id))
if (!course) {
return res.status(404).send('The course with the given ID was not found!')
}
// 删除课程
const targetIndex = courses.indexOf(course)
console.log(targetIndex)
courses.splice(targetIndex, 1)
res.send(course)
})
来源:CSDN
作者:cell006
链接:https://blog.csdn.net/funkstill/article/details/104184157