724 http:前后端分离,服务器端渲染,请求方式,响应状态码,ajax,Fetch,文件上传

前后端分离的优势


网页的渲染过程 – 服务器端渲染


~


网页的渲染过程 – 前后端分离


~


HTTP的组成


HTTP的版本


HTTP的请求方式


HTTP Request Header(一)


HTTP Request Header(二)


HTTP Response响应状态码

https://developer.mozilla.org/zh-CN/docs/web/http/status
~

  • 200
  • 201:Created ,POST请求,创建新的资源,即创建新的数据
  • 301:重定向
  • 400:传参,或者请求地址,或者别的原因,导致服务器不能处理请求
  • 401:Unauthorized,未授权的错误,必须携带请求的身份信息,cookie、token,比如用户没登录
  • 403:Forbidden 客户端没有权限访问,被拒接,比如登录了,但是没权限
  • 404:url接口不存在
  • ....


返回错误码的方式401,2种不同的响应状态码的设计


HTTP Request Header


Chrome安装插件 - FeHelper


AJAX发送请求


XMLHttpRequest的state(状态)


XMLHttpRequest其他事件监听


响应数据和响应类型


HTTP响应的状态statu


GET/POST请求传递参数


ajax网络请求封装


延迟时间timeout和取消请求


认识Fetch和Fetch API


Fetch数据的响应(Response)


Fetch网络请求的演练


Fetch POST请求


XMLHttpRequest文件上传


Fetch文件上传


02_XHR-XHR请求的基本使用.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 1.创建XMLHttpRequest对象 【创建网络请求的AJAX对象】
      const xhr = new XMLHttpRequest();

      // 2.监听状态的改变(宏任务)
      xhr.onreadystatechange = function () {
        console.log(xhr);
        console.log('readyState---', xhr.readyState); // 一次输出1、2、3、4
        // console.log(xhr.response)

        if (xhr.readyState !== XMLHttpRequest.DONE) return;

        // 将字符串转成JSON对象(js对象)
        const resJSON = JSON.parse(xhr.response);
        const banners = resJSON.data.banner.list;
        console.log(banners);
      };

      // 3.配置请求open
      // method: 请求的方式(get/post/delete/put/patch...)
      // url: 请求的地址
      xhr.open('get', 'http://123.207.32.32:8000/home/multidata');

      // 4.发送请求(浏览器帮助发送对应请求)
      xhr.send();
    </script>
  </body>
</html>

03_XHR-XHR状态变化的监听.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>
    // 1.创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest()

    // 2.监听状态的改变(宏任务)
    // 监听四种状态
    xhr.onreadystatechange = function() {
      // 1.如果状态不是DONE状态, 直接返回
      if (xhr.readyState !== XMLHttpRequest.DONE) return

      // 2.确定拿到了数据
      console.log(xhr.response)
    }

    // 3.配置请求open
    xhr.open("get", "http://123.207.32.32:8000/home/multidata")

    // 4.发送请求(浏览器帮助发送对应请求)
    xhr.send()

  </script>

</body>
</html>

04_XHR-XHR发送同步的请求.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>
    // 1.创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest()

    // 2.监听状态的改变(宏任务)
    // 监听四种状态
    // xhr.onreadystatechange = function() {
    //   // 1.如果状态不是DONE状态, 直接返回
    //   if (xhr.readyState !== XMLHttpRequest.DONE) return

    //   // 2.确定拿到了数据
    //   console.log(xhr.response)
    // }

    // 3.配置请求open
    // async: false
    // 实际开发中要使用异步请求, 异步请求不会阻塞js代码继续执行
    xhr.open("get", "http://123.207.32.32:8000/home/multidata", false)

    // 4.发送请求(浏览器帮助发送对应请求)
    xhr.send()

    // 5.同步必须等到有结果后, 才会继续执行
    console.log(xhr.response)

    console.log("------")
    console.log("++++++")
    console.log("******")

  </script>

  <h2>script后续的h2元素</h2>

</body>
</html>

05_XHR-XHR其他事件的监听.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>

    const xhr = new XMLHttpRequest()
    // onload监听数据加载完成
    xhr.onload = function() {
      console.log("onload")
    }
    xhr.open("get", "http://123.207.32.32:8000/home/multidata")
    xhr.send()

  </script>

</body>
</html>

06_XHR-XHR响应数据和类型.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>

    // 1.
    const xhr = new XMLHttpRequest()

    // 2.onload监听数据加载完成
    xhr.onload = function() {
      // const resJSON = JSON.parse(xhr.response)
      console.log(xhr.response)
      // console.log(xhr.responseText)
      // console.log(xhr.responseXML)
    }

    // 3.告知xhr获取到的数据的类型
    xhr.responseType = "json"
    // xhr.responseType = "xml"

    // 4.配置网络请求
    // 4.1.json类型的接口
    xhr.open("get", "http://123.207.32.32:8000/home/multidata")
    // 4.2.json类型的接口
    // xhr.open("get", "http://123.207.32.32:1888/01_basic/hello_json")
    // 4.3.text类型的接口
    // xhr.open("get", "http://123.207.32.32:1888/01_basic/hello_text")
    // 4.4.xml类型的接口
    // xhr.open("get", "http://123.207.32.32:1888/01_basic/hello_xml")

    // 5.发送网络请求
    xhr.send()

  </script>

</body>
</html>

07_XHR-获取HTTP的状态码.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>
    
    // 1.创建对象
    const xhr = new XMLHttpRequest()

    // 2.监听结果
    xhr.onload = function() {
      console.log(xhr.status, xhr.statusText)
      // 根据http的状态码判断是否请求成功
      if (xhr.status >= 200 && xhr.status < 300) {
        console.log(xhr.response)
      } else {
        console.log(xhr.status, xhr.statusText)
      }
    }

    xhr.onerror = function() {
      console.log("onerror", xhr.status, xhr.statusText)
    }

    // 3.设置响应类型
    xhr.responseType = "json"

    // 4.配置网络请求
    // xhr.open("get", "http://123.207.32.32:8000/abc/cba/aaa")
    xhr.open("get", "http://123.207.32.32:8000/home/multidata")

    // 5.发送网络请求
    xhr.send()
  </script>

</body>
</html>

08_XHR-GET-POST请求传参.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form class="info">
      <input type="text" name="username" />
      <input type="password" name="password" />
    </form>
    <button class="send">发送请求</button>

    <script>
      const formEl = document.querySelector('.info');
      const sendBtn = document.querySelector('.send');

      sendBtn.onclick = function () {
        // 创建xhr对象
        const xhr = new XMLHttpRequest();

        // 监听数据响应
        xhr.onload = function () {
          console.log(xhr.response);
        };

        // 配置请求
        xhr.responseType = 'json';

        // 1.传递参数方式一: get -> query
        // xhr.open("get", "http://123.207.32.32:1888/02_param/get?name=why&age=18&address=广州市")

        // 2.传递参数方式二: post -> urlencoded
        // xhr.open("post", "http://123.207.32.32:1888/02_param/posturl")
        // // 发送请求(请求体body)
        // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        // xhr.send("name=why&age=18&address=广州市")

        // 3.传递参数方式三: post -> formdata 【如果有表单,是application/x-www-form-urlencoded来编码的,默认RequestHeader的Content-type是这种格式,不需要设置。】
        // xhr.open("post", "http://123.207.32.32:1888/02_param/postform")
        // const formData = new FormData(formEl) // formElement对象转成FormData对象
        // xhr.send(formData)

        // 4.传递参数方式四: post -> json
        xhr.open('post', 'http://123.207.32.32:1888/02_param/postjson');
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.send(JSON.stringify({ name: 'why', age: 18, height: 1.88 }));
      };
    </script>
  </body>
</html>


09_XHR-Ajax网络请求封装.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>

    // 练习hyajax -> axios
    function hyajax({
      url,
      method = "get",
      data = {},
      headers = {}, // token
      success,
      failure
    } = {}) {
      // 1.创建对象
      const xhr = new XMLHttpRequest()

      // 2.监听数据
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          success && success(xhr.response)
        } else {
          failure && failure({ status: xhr.status, message: xhr.statusText })
        }
      }

      // 3.设置类型
      xhr.responseType = "json"

      // 4.open方法
      if (method.toUpperCase() === "GET") {
        const queryStrings = []
        for (const key in data) {
          queryStrings.push(`${key}=${data[key]}`)
        }
        url = url + "?" + queryStrings.join("&")
        xhr.open(method, url)
        xhr.send()
      } else {
        xhr.open(method, url)
        xhr.setRequestHeader("Content-type", "application/json")
        xhr.send(JSON.stringify(data))
      }

      return xhr
    }

    // 调用者
    hyajax({
      url: "http://123.207.32.32:1888/02_param/get",
      method: "GET",
      data: {
        name: "why",
        age: 18
      },
      success: function(res) {
        console.log("res:", res)
      },
      failure: function(err) {
        // alert(err.message)
      }
    })

    // hyajax({
    //   url: "http://123.207.32.32:1888/02_param/postjson",
    //   method: "post",
    //   data: {
    //     name: "jsondata",
    //     age: 22
    //   },
    //   success: function(res) {
    //     console.log("res:", res)
    //   },
    //   failure: function(err) {
    //     // alert(err.message)
    //   }
    // })

  </script>

</body>
</html>

10_XHR-Ajax网络请求工具.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <!-- <script src="./utils/hyajax.js"></script> -->
  <script src="./utils/hyajax_promise.js"></script>
  <script>
    const promise = hyajax({
      url: "http://123.207.32.32:1888/02_param/get",
      data: {
        username: "jie",
        password: "123456"
      }
    })

    promise.then(res => {
      console.log("res:", res)
    }).catch(err => {
      console.log("err:", err)
    })
  </script>

</body>
</html>

11_XHR-超时时间-取消请求.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <button>取消请求</button>

  <script>
    const xhr = new XMLHttpRequest()

    xhr.onload = function() {
      console.log(xhr.response)
    }
    xhr.onabort = function() {
      console.log("请求被取消掉了")
    }
    
    xhr.responseType = "json"

    // 1.超市时间的设置
    xhr.ontimeout = function() {
      console.log("请求过期: timeout")
    }
    // timeout: 浏览器达到过期时间还没有获取到对应的结果时, 取消本次请求
    // xhr.timeout = 3000
    xhr.open("get", "http://123.207.32.32:1888/01_basic/timeout")

    xhr.send()

    // 2.手动取消结果
    const cancelBtn = document.querySelector("button")
    cancelBtn.onclick = function() {
      xhr.abort()
    }

  </script>

</body>
</html>

12_Fetch-Fetch函数基本使用.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script>

    // 1.fetch发送get请求
    // 1.1.未优化的代码
    // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
    //   // 1.获取到response
    //   const response = res

    //   // 2.获取具体的结果
    //   response.json().then(res => {
    //     console.log("res:", res)
    //   })
    // }).catch(err => {
    //   console.log("err:", err)
    // })

    // 1.2. 优化方式一:
    // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
    //   // 1.获取到response
    //   const response = res
    //   // 2.获取具体的结果
    //   return response.json()
    // }).then(res => {
    //   console.log("res:", res)
    // }).catch(err => {
    //   console.log("err:", err)
    // })

    // 1.3. 优化方式二:
    // async function getData() {
    //   const response = await fetch("http://123.207.32.32:8000/home/multidata")
    //   const res = await response.json()
    //   console.log("res:", res)
    // }
    // getData()


    // 2.post请求并且有参数
    async function getData() {
      // const response = await fetch("http://123.207.32.32:1888/02_param/postjson", {
      //   method: "post",
      //   // headers: {
      //   //   "Content-type": "application/json"
      //   // },
      //   body: JSON.stringify({
      //     name: "why",
      //     age: 18
      //   })
      // })
      
      const formData = new FormData()
      formData.append("name", "why")
      formData.append("age", 18)
      const response = await fetch("http://123.207.32.32:1888/02_param/postform", {
        method: "post",
        body: formData
      })

      // 获取response状态
      console.log(response.ok, response.status, response.statusText)

      const res = await response.json()
      console.log("res:", res)
    }
    getData()

  </script>

</body>
</html>

13_XHR-文件上传的接口演练.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input class="file" type="file" />
    <button class="upload">上传文件</button>

    <script>
      // xhr/fetch

      const uploadBtn = document.querySelector('.upload');
      uploadBtn.onclick = function () {
        // 1.创建对象
        const xhr = new XMLHttpRequest();

        // 2.监听结果
        xhr.onload = function () {
          console.log(xhr.response);
        };

        xhr.onprogress = function (event) {
          console.log(event);
        };

        xhr.responseType = 'json';
        xhr.open('post', 'http://123.207.32.32:1888/02_param/upload');

        // 表单
        const fileEl = document.querySelector('.file');
        const file = fileEl.files[0];

        const formData = new FormData();
        formData.append('avatar', file);

        xhr.send(formData);
      };
    </script>
  </body>
</html>


14_Fetch-文件上传的接口演练.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <input class="file" type="file">
  <button class="upload">上传文件</button>
  
  <script>

    // xhr/fetch

    const uploadBtn = document.querySelector(".upload")
    uploadBtn.onclick = async function() {
      // 表单
      const fileEl = document.querySelector(".file")
      const file = fileEl.files[0]

      const formData = new FormData()
      formData.append("avatar", file)

      // 发送fetch请求
      const response = await fetch("http://123.207.32.32:1888/02_param/upload", {
        method: "post",
        body: formData
      })
      const res = await response.json()
      console.log("res:", res)
    }

  </script>

</body>
</html>

posted on 2022-07-09 22:33  冲啊!  阅读(179)  评论(0编辑  收藏  举报

导航