[TOC]

:::info

已经2021年了,现在还有人用表单请求吗(⊙﹏⊙),让我们看看表单请求的例子

  • action:请求地址
  • method:方法请求类型
  • enctype:以什么格式传输文件
  • input type=’submit’:点击后就自动请求 :::

    <form 
          action="http://localhost:8080/formTest" 
          method="post" 
          enctype="application/x-www-form-urlencoded">
        <input type="text" name="name" value="joe">
        <input type="text" name="pwd" value="123456">
        <input type="submit" value="submit">
    </form>
    

    :::success 我们可以看到这样其实很不方便:

  • 我们需要处理一下数据之类,做一些封装都很不方便。

  • 然后要控制什么时候的发送都是通过一个点击事件去完成,其实和js代码的非常的不融合在一起
  • 对于一些不要表单的请求就写一个隐藏表单再点击吗?
  • 然后发送以后重定向还需要刷新,非常麻烦,

所以就诞生下面几种方法: :::

ajax

  • 简介:异步的 JavaScript 和 XML,不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容

    1. 创建xhr对象

  • 正常创建:let xhr = new XMLHttpRequest()

  • IE5,6的兼容创建:var xhr = new ActiveXObject("Microsoft.XMLHTTP")

    2. 向服务器发送请求以及设置请求头

  • 规定好请求:xhr.open(method, url, async)

  • 设置请求头:xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
  • 发出请求:xhr.send()

    3. 响应请求

  • 监听请求状态readyState的变化,当readyState===4时候就可以判断返回的状态码

    xhr.onreadystatechange = () => {if (readyState === 4) {/**处理**/}}
    
  • readyState

    • 0:请求未初始化
    • 1:服务器连接已经建立
    • 2:请求已接收
    • 3:请求处理中
    • 4:请求已完成,且响应已就绪

      一个完整的例子

      <body>
      <input type="button" value="ok" id="btn">
      <script>
      let btn = document.getElementById("btn");
      btn.onclick = function () {
       // 1.创建实例
       var xhr = new XMLHttpRequest();
       console.log(xhr.readyState); // 0  
       // 2 .链接服务器 请求方式   请求文件  异步或同步 异步
       xhr.open("GET", "http://localhost:8080/", true); 
       console.log(xhr.readyState); // 1
       // 3. 发送请求
       xhr.send();
       console.log(xhr.readyState); // 1
       // 4. 接收返回
       xhr.onreadystatechange = function () {
       console.log(xhr.readyState); // 期间会打印出 2,3,4,因为一旦readyState的状态change就会触发函数
       // 5. 判断readyState===4,说明请求结束
         if (xhr.readyState === 4) { 
           // 6. 判断状态码是否处于正常值
           if (xhr.status >= 200 && xhr.status < 300) { 
             console.log(xhr.responseText);
           }
         }
       }
      }  
      </script>
      </body>
      

      fetch基本用法

  • 简介:该方法提供了一种简单,合理的方式来跨网络异步获取资源。

  • 特点:
    • 当接收到一个代表错误的 HTTP 状态码时,从 fetch() 返回的 Promise 不会被标记为 reject,即使响应的 HTTP 状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (如果响应的 HTTP 状态码不在 200 - 299 的范围内,则设置 resolve 返回值的 ok 属性为 false ),仅当网络故障时或请求被阻止时,才会标记为 reject。
    • fetch 不会发送跨域 cookies

      1. 一个最简单的fetch请求

      fetch('http://localhost/test').then(res => console.log(res))
      

      2. 完整版的fetch封装

      ```javascript async function fetchData(url, type = ‘post’ data = {}) { const res = await fetch(‘http://localhost/test‘, { method: ‘post’, headers: { ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(data) }) return res; }

fetchData(‘http://localhost/test').then(res => console.log(res))

<a name="qUvP1"></a>
#### 3. 怎么上传文件的

- 利用input和formData和fetch
```javascript
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())

axios

  • 简介:是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
  • 安装:npm install axios
  • cdn引入:<script src="[https://unpkg.com/axios/dist/axios.min.js"></script>](https://unpkg.com/axios/dist/axios.min.js"></script>)

    1. 基本的请求

  • 直接method(get, post, delete, put)请求

  • 基本格式

    • axios.request(config)
    • axios.get(url[, config])
    • axios.delete(url[, config])
    • axios.head(url[, config])
    • axios.options(url[, config])
    • axios.post(url[, data[, config]])
    • axios.put(url[, data[, config]])
    • axios.patch(url[, data[, config]])
    • axios.方法(地址,{数据}, {配置})
      // get(1)
      axios.get('http://localhost:8080/test/?id=111').then(res => {console.log('结果' + res)})
      // get(2)
      axios.get('http://localhost:8080/test', {params: {id: 111}}).then(res => {console.log('结果' + res)})
      // post
      axios.post('http://localhost:8080/test', {id: 111}).then(res => {console.log('结果' + res)})
      // put
      axios.put('http://localhost:8080/test', {id: 111}).then(res => {console.log('结果' + res)})
      // delete
      axios.delete('http://localhost:8080/test', {id: 111}).then(res => {console.log('结果' + res)})
      
  • 只配置参数请求,即所有的参数都配置进去对象里面

    • axios({method: ‘get’, url: ‘http://localhost:8080/test‘, headers: {}}).then()
      axios({method: 'get', url: 'http://localhost:8080/test', params: {name: 'joe'}}).then(res => {
        console.log(res)
      })
      

      2. 配置默认值

  • 配置默认值:axios.defaults.method = ‘get’

  • 加了默认请求的时候就会默认用这个配置 ```javascript axios.defaults.method = ‘post’; axios.defaults.baseURL = ‘http://localhost:8080‘ axios({url: ‘/test’}).then(res => { console.log(res) })

// 上面这段等价于

axios({url: ‘http://localhost:8080/test‘, method: ‘post’}).then(res => { console.log(res) })

<a name="U7Gf8"></a>
#### 3. 创建请求实例

- 创建实例的好处,就是你可以创建两个实例分配给他们配置默认值,去向两个服务器发去请求,就不用改来改去
```javascript
service = axios.create({
  // 这里里面配置默认值
  baseURL: 'http://localhost:8080'
})

4. 配置拦截器

  • 通过配置请求拦截器和返回拦截器,对请求的配置可动态更改,对返回的结果和做些统一处理
    • _axios_.interceptors.request.use(resloved, rejected)
    • _axios_.interceptors.response.use(resloved, rejected)
      axios.interceptors.request.use(config => {
      config.data.id = 888; // 原本的id为666,请求拦截修改程888再return配置
      return config;
      }, error => {
      console.log(error)
      })
      axios.interceptors.response.use(res => {
      return res.data; // 原本为一个复杂的对象,我们可以统一处理再return结果出去
      }, error => {
      console.log(error)
      })
      axios({method: 'post', baseURL: 'http://localhost:8080/test', data: {id: 666}}).then(res => {
      console.log(res)
      })
      

      5. 取消请求

      ```html <!doctype html>
      请求
      取消
<a name="TsXyQ"></a>
## 常用状态码
```javascript

            /**
             * 200 表示从客户端发来的请求在服务器端被正常处理了。
             204 表示请求处理成功,但没有资源返回。
             301 表示永久性重定向。该状态码表示请求的资源已被分配了新的URI,以后应使用资源现在所指的URI。
             302 表示临时性重定向。
             304 表示客户端发送附带条件的请求时(指采用GET方法的请求报文中包含if-matched,if-modified-since,if-none-match,if-range,if-unmodified-since任一个首部)服务器端允许请求访问资源,但因发生请求未满足条件的情况后,直接返回304Modified(服务器端资源未改变,可直接使用客户端未过期的缓存)
             400 表示请求报文中存在语法错误。当错误发生时,需修改请求的内容后再次发送请求。
             401 表示未授权(Unauthorized),当前请求需要用户验证
             403 表示对请求资源的访问被服务器拒绝了
             404 表示服务器上无法找到请求的资源。除此之外,也可以在服务器端拒绝请求且不想说明理由时使用。
             500 表示服务器端在执行请求时发生了错误。也有可能是Web应用存在的bug或某些临时的故障。
             503 表示服务器暂时处于超负载或正在进行停机维护,现在无法处理请求。
             */