fetch皮毛

fetch概述

1.基本特性

  • ​ 更加简单的数据获取方式,功能更强大,更灵活,可以看做是xhr的升级版
  • ​ 基于Promise实现

2.语法结构

fetch(url).then(fn2)
    .then(fn3)
    ...
    .catch(fn)

fetch('/abc').then(data=>{
    return data.text();
}).then(ret=>{
    //注意这里得到的才是最终的数据
    console.log(ret);
})
//(text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据)

fetch请求参数

1.常用配置选项

methods(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)

body(String):HTTP的请求参数

headers(Object):HTTP的请求头,默认为{}

fetch('/abc',{
    method:'get'
}).then(data=>{
    return data.text();
}).then(ret=>{
    //注意这里的到的才是最终的数据
    console.log(ret);
});

2.get请求方式的参数传递

fetch('/abc?id=123').then(data=>{
    return data.text();
}).then(ret=>{
     //注意这里的到的才是最终的数据
    console.log(ret);
})

 fetch('/abc/123',{
    method:'get'
}).then(data=>{
    return data.text();
}).then(ret=>{
    //注意这里的到的才是最终的数据
    console.log(ret);
});

3.DELETE请求方式的参数传递

fetch('/abc/123',{
    method:'delete'
}).then(data=>{
    return data.text();
}).then(ret=>{
    //注意这里的到的才是最终的数据
    console.log(ret);
})

4.POST请求方式的参数传递

fetch('/books',{
    method:'post',
    body:'uname=lisi&pwd=123',
    headers:{
        'Content-Type':'application/x-www-form-urlencoded',
    }
}).than(data=>{
    return data.text();
}).then(ret=>{
    console.log(ret);
})

fetch('/books',{
    method:'post',
    body:JSON.stringfy({
        uname:'lisi',
        age:12
    })
    headers:{
    	'Content-Type':'application/json',
	}
}).then(data=>{
    return data.text();
}).then(ret=>{
    console.log(ret);
})

5.PUT请求方式的参数传递

fetch('/books/123',{
    method:'put',
    body:JSON.stringfy({
        uname:'lisi',
        age:12
    })
    headers:{
    	'Content-Type':'application/json',
	}
}).then(data=>{
    return data.text();
}).then(ret=>{
    console.log(ret);
})

fetch响应结果

响应数据格式

​ text():将返回体处理成字符串类型

​ json():将返回结果和JSON.parse(responseText)一样

fetch('/data' then(data)=>{
    //return data.text();
    return data.json();
}).then(ret=>{
    console.log(ret);
})

原文地址:https://www.cnblogs.com/wahaha-/p/14051096.html