In-depth analysis of axios source code HTTP and json-server

1. HTTP related content

  1. The basic process of front-end and back-end interaction is as follows:
  • And after application of the transmission from the server to the browser HTTPrequest (packet)
  • After the back-end server receiving the request, the server application processing the scheduling request, the server returns to the browser HTTPin response (response packet)
  • The browser receives the response, parses and displays the response body/calls the monitoring callback
  1. HTTP The request message is as follows:
  • Request line: Request method /url, as shown below:
    method url GET /product_detail?id=2 POST /login
  • A plurality of request header: request header of a name:valuecomposition as Host/Cookie/Content-Typefollows:
    Host: www.baidu.com 
    Cookie: BAIDUID=AD3B0FA706E; BIDUPSID=AD3B0FA706; 
    Content-Type: application/x-www-form-urlencoded 或者 application/json
    
  • The request body is as follows:
    username=tom&pwd=123 
    {
          
          "username": "tom", "pwd": 123}
    
  1. HTTP The response message is as follows:
  • Response line: response status code/corresponding text, such as status statusText
  • Multiple response headers: For example Content-Type / Set-Cookie 头, as shown below:
    Content-Type: text/html;charset=utf-8
    Set-Cookie: BD_CK_SAM=1;path=/
    
  • Response body, such as html 文本 /json 文本/js/css/图片
  1. post The format of the request body text parameter is as follows:
  • Content-Type: application/x-www-form-urlencoded;charset=utf-8
    For the keys with key = connection with the parameters, parameter between parameters &connected
    example:name=%E5%B0%8F%E6%98%8E&age=12
  • Content-Type: application/json;charset=utf-8 用于json字符串参数
    E.g: {"name": "%E5%B0%8F%E6%98%8E", "age": 12}
  • Content-Type: multipart/form-dataFor file upload requests
  1. Common response status codes are as follows:
  • 200 OKRequest is successful, generally used for GETthe POSTrequest
  • 201 Created Created, successfully requested and created a new resource
  • 401 Unauthorized Unauthorized/request requires user authentication
  • 404 Not Found The server cannot find the resource based on the client's request
  • 500 Internal Server Error An internal server error prevented the request to complete
  1. Different types of requests and their effects are as follows;
  • GET: Read data from the server
  • POST: Add new data to the server
  • PUT: Update the existing data on the server side
  • DELETE: Delete server-side data
  1. API The classification is as follows:
  • REST API: restful, As follows:
    • Transmission request CRUDwhich requests the operation mode determined by
    • Multiple operations can be performed on the same request path
    • The request method will be used GET/POST/PUT/DELETE
  • Not REST API:, restlessas follows:
    • Request method does not determine the requested CRUDoperation
    • A request path corresponds to only one operation
    • Generally only GET/POST
  • Test: You can use json-serverquickly build analog rest apiinterfaces

2. Related content of json-server

  1. json-server: Used to quickly build REST APItools package.
  2. Use json-serverit as follows:
  • Online documentation: https://github.com/typicode/json-server
  • download: npm install -g json-server
  • Create a database under the target root jsonfile:db.json
    {
          
           
        "posts": [ {
          
           "id": 1, "title": "json-server", "author": "typicode" } ],
        "comments": [ {
          
           "id": 1, "body": "some comment", "postId": 1 } ],
        "profile": {
          
           "name": "typicode" } 
    } 
    
  • Start the server and execute the command: json-server --watch db.json
  1. Use a browser to access the test
  • http://localhost:3000/posts
  • http://localhost:3000/posts/1
  1. Use axiosaccess test code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <button onclick="testGet()">GET请求</button>
    <button onclick="testPost()">POST请求</button>
    <button onclick="testPut()">PUT请求</button>
    <button onclick="testDelete()">DELETE请求</button>
  </div>

  <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
  <script>
    /* 1. GET请求: 从服务器端获取数据*/
    function testGet() {
     
     
      // axios.get('http://localhost:3000/posts')
      // axios.get('http://localhost:3000/posts/1')
      // 获取 id 为 1 的参数
      axios.get('http://localhost:3000/posts?id=1')
        .then(response => {
     
     
          console.log('/posts get', response.data)
        })
    }

    /* 2. POST请求: 向服务器端添加新数据*/
    function testPost() {
     
     
      // 保存数据
      axios.post('http://localhost:3000/posts', {
     
     "title": "json-server3", "author": "typicode3"})
        .then(response => {
     
     
          console.log('/posts post', response.data)
        })
    }

    /* 3. PUT请求: 更新服务器端已经数据 */
    function testPut() {
     
     
      axios.put('http://localhost:3000/posts/3', {
     
     "title": "json-server...", "author": "typicode..."})
        .then(response => {
     
     
          console.log('/posts put', response.data)
        })
    }

    /* 4. DELETE请求: 删除服务器端数据 */
    function testDelete() {
     
     
      axios.delete('http://localhost:3000/posts/3')
        .then(response => {
     
     
          console.log('/posts delete', response.data)
        })
    }

  </script>
</body>
</html>

db.json :

{
    
    
  "posts": [
    {
    
    
      "title": "json-server+++",
      "author": "typicode+++",
      "id": 1
    },
    {
    
    
      "id": 3
    },
    {
    
    
      "title": "json-server3",
      "author": "typicode3",
      "id": 6
    },
    {
    
    
      "title": "json-server4",
      "author": "typicode4",
      "id": 7
    }
  ],
  "comments": [
    {
    
    
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    
    
    "name": "typicode"
  }
}

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/106988767