fetch和ajax 的主要区别
1、fetch()返回的promise将不会拒绝http的错误状态,即使响应是一个HTTP 404或者500 2、在默认情况下 fetch不会接受或者发送cookies
特点
fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
老版本浏览器可能不支持
相关API
GET请求
fetch(url).then(function(response) {    return response.json()  }).then(function(data) {    console.log(data)  }).catch(function(e) {    console.log(e)  });        POST请求
fetch(url, {    method: "POST",    body: JSON.stringify(data),  }).then(function(data) {    console.log(data)  }).catch(function(e) {    console.log(e)  })案例
search =async () => {    // 发布消息 publish    // 获取用户的输入 (连续解构赋值+重命名)    const { keyWordElement: { value: keyWord } } = this    // 请求成功后通知App更新状态    PubSub.publish('atguigu',{isFirst:false,isLoading:true})    // 发送网络请求    // 当自己在3000时 可以省略http://localhost:3000    // /api1 必须跟在3000后面    //#region     // 发送网络请求 ——— 使用axios 发送   /*  axios.get(`http://localhost:3000/api1/search/users?q=${keyWord}`).then(      response => {        // 请求成功后通知App更新状态        PubSub.publish('atguigu',{isLoading:false,users:response.data.items})       },      error => {        // 请求失败后通知App更新状态         // 不能直接输出error  只能输出 error.message         PubSub.publish('atguigu',{isLoading:false,err:error.message})      }    ) */    //#endregion       // 发送网络请求 —— 使用fetch发送 (未优化)    /* fetch(`/api1/search/users2?q=${keyWord}`).then(      response => {        console.log('联系服务器成功了')        return response.json()      },      error => {        console.log('联系服务器失败了', error)        return new Promise(()=>{})      }    ).then(      response => {        console.log('获取数据成功了',response)      },      error => {        console.log('获取数据失败了', error)      }    ) */    // 发送网路请求 —— 使用fetch发送(优化)    try {      const response = await fetch(`/api1/search/users2?q=${keyWord}`)      const data = await response.json()      console.log(data)      PubSub.publish('atguigu', { isLoading: false, users: data.items })    } catch (error) {      console.log('请求错误',error)      PubSub.publish('atguigu', { isLoading:false,err:error.message})    }  }附录小知识
让浏览器处于离线状态
进入开发者工具 找到 Netword 然后将Online改成 Offline 当浏览器处于离线状态时 fetch 请求联系服务器才会失败
原文:https://juejin.cn/post/7096322484831518750