普通接口设计
-
只用到get和post接口
-
接口的地址一般由动词+名词构成
-
每个接口的地址都不一样
例如:
接口名:localhost:8080/getarticle 类型:get 功能:获取文章信息
接口名:localhost:8080/addarticle 类型:post 功能:添加新文章
接口名:localhost:8080/delarticle 类型:post 功能:删除文章
接口名:localhost:8080/updatearticle 类型:post 功能:编辑文章
//------------下面是普通的api设计---------------
app.get('/getarticle',(req,res)=>{
res.send('获取')
})
app.post('/addarticle',(req,res)=>{
res.send('添加')
})
app.post('/delarticle',(req,res)=>{
res.send('删除')
})
app.post('/updatearticle',(req,res)=>{
res.send('编辑')
})
而RESTful风格的接口可以更节省代码更可观.
RESTful接口设计
区别上述功能,主要依靠接口名称和请求类型而在restful设计中,它们应该是这样的:
接口名:localhost:8080/articles 类型:get 功能:获取文章信息
接口名:localhost:8080/articles 类型:post 功能:添加新文章
接口名:localhost:8080/articles 类型:delete 功能:删除文章
接口名:localhost:8080/articles 类型:put 功能:编辑文章
RESTful设计是:
-
通过URL设计资源。接口名一般都是名词,不包含动词。
-
请求方式(get,post,delete,put)决定资源的操作类型
const express = require('express')
const app = express();
app.get('/articles',(req,res)=>{
res.send('获取')
})
app.post('/articles',(req,res)=>{
res.send('添加')
})
app.delete('/articles',(req,res)=>{
res.send('删除')
})
app.put('/articles',(req,res)=>{
res.send('编辑')
})
app.listen(8080,()=>{
console.log(8080);
})