用Nodejs实现RESTFUL风格接口,返回常见HTTP状态码

1,765 阅读1分钟

本文正在参与 “网络协议必知必会”征文活动

什么是RESTFUL风格接口

图片.png

CURD约定

图片.png

RESTFUL优点

  • 客户端无状态(简化开发)
  • 资源独立、接口间独立(缓存好设计)
  • 对协议依赖不重要(可迁移)

常见HTTP状态码

图片.png

2xx状态码

图片.png

3xx状态码

图片.png

4xx状态码

图片.png

5xx状态码

图片.png

Node实现

解析Body和2xx状态码

method和解析body

图片.png

  • 用Node+express实现一个简单的服务
const express = require('express')
const app = express()

app.get('/greetings', (req, res) => {
  res.send('Hi!')
})

app.post('/product', (req, res) => {
  // 请求头
  const contentType = req.headers['content-type']
  // console.log(contentType)
  let body = null
  
 
  let requestText = ""
  req.on('data', (buffer) => {
    // 8bit - byte 八进制 字节流 有最大长度限制
    requestText += buffer.toString('utf-8')
    // console.log(buffer.toString('utf-8').length)
  })

  req.on('end', () => {
    // console.log(requestText.length)
    switch(contentType){
      case 'application/json':
        body = JSON.parse(requestText)
        // console.log(body)
        res.set('content-type', 'application/json')
        res.status(201).send(JSON.stringify({success: 1}))
        break
    }
  })

  
})

app.put('/product/:id', (req, res) => {
  console.log(req.params.id)
  res.sendStatus(204)
})

app.delete('/product/:id', (req, res) => {
  console.log(req.params.id)
  res.sendStatus(204)
})

app.listen(3000, () => {
  console.log('listen on 3000')
})
  • 在控制台中输入
fetch(
    "/product", 
    {
        method: 'POST', 
        headers: {'content-type': 'application/json'}, 
        body: JSON.stringify({name: "".padStart(100000, "A")})
    }
)
  • 查看返回状态 图片.png

跳转Header和3xx状态码

重定向观察

const express = require('express')
const app = express()

app.get('/301', (req, res) => {
  res.redirect(301, '/def')
})
app.get('/302', (req, res) => {
  res.redirect(302, '/def')
})
app.get('/303', (req, res) => {
  res.redirect(303, '/def')
})

app.post('/302', (req, res) => {
  res.redirect(302, '/def')
})

app.post('/307', (req, res) => {
  res.redirect(307, '/def')
})

app.get('/def', (req, res) => {
  res.send("This is def(GET)")
})

app.listen(3000, () => {console.log('listen on 3000')})
fetch('/301', {method: 'GET'})
  • get/301 => get/def 永久重定向

图片.png

fetch('/302', {method: 'GET'})
  • get/302 => get/def

图片.png

fetch('/303', {method: 'GET'})
  • get/303 => get/def

图片.png

fetch('/302', {method: 'POST'})
  • post /302 => get/def

图片.png

fetch('/307', {method: 'POST'})
  • post /307 => post/def 没有post/def 接口,返回404

图片.png

  • 新增 post/def接口,再来试一下
app.post('/def', (req, res) => {
  res.send("This is def(POST)")
})

图片.png

图片.png

错误处理:4xx和5xx

app.get('/abc', (req, res) => {
  res.sendStatus(404)
})

图片.png

app.get('/abc', (req, res) => {
  throw "Error"
})

图片.png

app.get('/abc', (req, res) => {
  res.sendStatus(502)
})

图片.png