提供数据地址: http://jsonplaceholder.typicode.com/ 这个网站模拟了一部分数据 https://dog.ceo/api/breeds/image/random 随机请求一张图片地址

什么是fetch
ES2017中新增的特性,与传统的ajax相比,其实它的作用是替代浏览器原生的XMLHttpRequest异步请求,我们在日常的开发中,基本不会自己去写XMLHttpRequest,主要是太复杂了,都是使用已经封装好了的各种插,件常用的有jquery,npm包管理工具也提供了axios,request等模块。而有了fetch后我们就可以在不用这些插件的情况下快速简单的实现异步请求了

Fetch() 是 Fetch API 中 JavaScript window 对象的一个方法。它是内置的,所以开发者无需进行任何安装。Fetch() 允许我们在不安装其他库的情况下异步请求数据。

fetch是基于标准promise实现的,可以使用async/await

fetch基础操作

语法:

fetch(请求的地址).then(function(data) {

return data.text(); // 通过调用text返回promise对象

}).then(function(data) {

console.log(data); // 得到真正的结果
})

案例:请求jsonplaceholder网站中的数据
let res = fetch('http://jsonplaceholder.typicode.com/posts'); // 请求数据
res.then(data=>{
    return data.json(); // 使用json方法返回数据,格式为json
    return data.text(); // 还可以使用text,返回字符串格式
}).then(allIn=>{
    console.log(allIn); // 打印数据
});
如何处理请求出错

请求路径出错,需要添加判断,然后使用throw返回错误信息

let res = fetch('https://dog.ceo/api/breeds/image/random0');
res.then(response=>{
  if(response.ok){
      return response.json();
  }
  // throw '网络错误!'; // 简单写法
  throw new Error('网络错误!'); // 官方推荐写法
})
.then(data=>console.log(data));

2.fetch的其他请求方法

常用的请求方式有很多:get查看/post创建/put更新/delete删除

1、GET请求会向数据库发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产生副作用。无论进行多少次操作,结果都是一样的。

2、与GET不同的是,PUT请求是向服务器端发送数据的,从而改变信息,该请求就像数据库的update操作一样,用来修改数据的内容,但是不会增加数据的种类等,也就是说无论进行多少次PUT操作,其结果并没有不同。

3、POST请求同PUT请求类似,都是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。

4、DELETE请求顾名思义,就是用来删除某一个资源的,该请求就像数据库的delete操作。

get请求方式的参数传递 (传统方式)
fetch('http://localhost:3000/books?id=123', {
    method: 'get'
}).then(function(data) {
    return data.text();
}).then(function(data) {
    console.log(data);
})
post请求
fetch('http://localhost:3000/books', {
    method: 'post',
    body: JSON.stringify({ // json字符串形式
        uname: 'kun',
        pwd: '321'
    }),
    headers: {
        'Content-Type': 'application/json' // json格式头
    }
}).then(function(data) {
    return data.text();
}).then(function(data) {
    console.log(data);
})
put修改
fetch('http://localhost:3000/goods/10', {
    method: 'put',
    body:JSON.stringify({
        goodsname: "帽子2",
        price:200
    })
}).then(res => {
    return res.json();
}).then(data => {
    console.log(data);
})
delete删除
fetch('http://localhost:3000/goods/1', {
    method: 'delete'
}).then(res => {
    return res.json();
}).then(data => {
    console.log(data);
})
使用post给连接添加数据
<button id='btn'>添加信息</button>
<input type="text" id="uname">
  <script>
  let oBtn = document.querySelector('#btn');
  let uName = document.querySelector('#uname');
  oBtn.addEventListener('click',()=>{
    fetch('http://jsonplaceholder.typicode.com/users',{
      method:'post',
      body:JSON.stringify({name:uName.value}), // 需要转为服务器能够识别的json格式
      headers:{
        "Content-Type":"application/json"
      }
    })
      .then(res=>res.json())
      .then(data=>console.log(data))
  })
</script>

基本语法格式:https://www.cnblogs.com/Alisa-k/p/12673377.html

  1. 案例:使用async和await实现请求数据
    fetch返回的是一个异步的请求,如果想要把请求变成同步可以使用await await: 操作符用于等待一个 Promise 对象, 它只能在异步函数 async function 内部使用。

但是:await只有在async中才可以使用; async:函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。

  1. 使用fetch请求数据
let url = 'https://gorest.co.in/public/v1/users';
fetch(${url}/3434/)
.then(res=>res.json())
.then(json=>console.log(json.data.name))

fetch(${url}/3433/)
.then(res=>res.json())
.then(json=>json.data)
.then(data=>console.log(${data.name}))

fetch(${url}/3432/)
.then(res=>res.json())
.then(json=>json.data)
.then(data=>console.log(${data.name}))
console.log('------分割线--------');
  1. 使用async和await请求数据
  let show = async ()=>{
  let url = 'https://gorest.co.in/public/v1/users';

  let res1 = await fetch(${url}/3434/);
  let json1 = await res1.json();
  let name1 = await json1.data.name;

  let res2 = await fetch(${url}/3433/);
  let json2 = await res2.json();
  let name2 = await json2.data.name;

  let res3 = await fetch(${url}/3432/);
  let json3 = await res3.json();
  let name3 = await json3.data.name;

  console.log(name1);
  console.log(name2);
  console.log(name3);
}
show();
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐