拓展一下知识 了解其他的Api接口 想知道就点进来看看吧

205 阅读2分钟

拓展介绍-RESTful接口(了解)

网络应用程序,分为前端和后端两个部分。当前的发展趋势,就是前端设备层出不穷(手机、平板、桌面电脑、其他专用设备…)。因此,必须有一种统一的机制,方便不同的前端设备与后端进行通信。这导致API构架的流行,甚至出现"APIFirst"的设计思想。RESTful API是目前比较成熟的一套互联网应用程序的API设计理论

REST(Representational State Transfer)表述性状态转换,REST指的是一组架构约束条件和原则。 如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。REST本身并没有创造新的技术、组件或服务,而隐藏在RESTful背后的理念就是使用Web的现有特征和能力, 更好地使用现有Web标准中的一些准则和约束。

符合REST规范的设计,我们称之为RESTful设计。 它的设计哲学是将服务器端提供的内容实体看作一个资源,并表现在url上。

普通接口设计

例如:
接口名: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设计中,它们应该是这样的:
接口名: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); 
})