1.什么是 RESTful?
RESTful 是一种特定的URL的风格,也就是路由的风格。
常见的http请求:get,post
RESTful则是面向资源的方式处理url:对于同一个资源操作,都在同一个URL进行,通过判断http请求的类型来决定做不同的事
假设 /user 是一个资源
传统的URL风格:
http://xxx.x.x.x/user/query/1 查询
http://xxx.x.x.x/user/save 保存
http://xxx.x.x.x/user/update 更新
http://xxx.x.x.x/user/delete/{id} 删除RESTful风格:
http://xxx.x.x.x/user/1 查询 (GET)
http://xxx.x.x.x/user 保存 (POST)
http://xxx.x.x.x/user 更新 (PUT)
http://xxx.x.x.x/user 删除 (DELETE)总结:用URL定位资源,http描述操作
2.用NodeJS实现 RESTful
知识点:NodeJS 使用的是顶层路由,每一个路由不一定对应一个文件,不需要有物理文件去映射路由
原生NodeJS实现:
const http = require('http')
const app = http.createServer((req, res) => {
if (req.method === 'POST') {
if (req.url === '/user') {
res.end(JSON.stringify({ 'messgae': '对user接口发起了post请求' }))
}
} else if (req.method === 'GET') {
if (req.url === '/user') {
res.end(JSON.stringify({ 'messgae': '对user接口发起了get请求' }))
}
}
})
app.listen(3200)