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")})
    
  • 查看返回状态

    跳转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 永久重定向
  • fetch('/302', {method: 'GET'})
    
  • get/302 => get/def
  • fetch('/303', {method: 'GET'})
    
  • get/303 => get/def
  • fetch('/302', {method: 'POST'})
    
  • post /302 => get/def
  • fetch('/307', {method: 'POST'})
    
  • post /307 => post/def 没有post/def 接口,返回404
  • 新增 post/def接口,再来试一下
  • app.post('/def', (req, res) => {
      res.send("This is def(POST)")
    

    错误处理:4xx和5xx

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

    图片.png

  • 【法医奇遇记】法医破案之HTTP协议状态码探秘
  • 30 道 Vue 面试题,内含详细讲解(涵盖入门到精通,自测 Vue 掌握程度)
  • 私信
     1,171