fetch / axios(和 ajax 一样,都是请求数据用的)(附:原生(fetch)的 get 、post 请求)

fetch和ajax的区别:fetch代码更加简洁,适用于更高版本浏览器。ajax可以监听到请求过程,兼容性好.......

 

fetch:

注意:由于Fetch API是基于Promise设计,旧浏览器不支持Promise,需要使用pollyfill es6-promise

fetch(url, options)
.then(function(response) {
// handle HTTP response
}, function(error) {
// handle network error
})

method(String): HTTP请求方法,默认为GET
body(String): HTTP的请求参数
headers(Object): HTTP的请求头,默认为{}
credentials(String):
默认为omit,忽略的意思,
也就是不带cookie;还有两个参数,
same-origin,意思就是同源请求带cookie;
include,表示无论跨域还是同源请求都会带cookie
 
body: 返回体,这里有处理返回体的一些方法

text(): 将返回体处理成字符串类型
json(): 返回结果和 JSON.parse(responseText)一样
blob(): 返回一个Blob,Blob对象是一个不可更改的类文件的二进制数据
arrayBuffer()
formData()

fetch  的 post / get 请求方式:
/*原生的方式    post  */
let xhr = new XMLHttpRequest;//1.先创建ajax对象
xhr.open('post','请求地址',true);//2.填写地址 (请求方式,?号前面的地址,默认为true表示异步)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');//3.设置请求头。固定写法
xhr.send('user='+ txt.value);//4.发送数据  (商量好的)字段+参数 => 'user=val'(字符串)
xhr.onload = function(){//5.等待服务器响应
    JSON.parse(xhr.responseText)//6.接收到数据,并开始处理
};

/*原生的方式    get  */
let xhr = new XMLHttpRequest;//1.创建对象
xhr.open('get','get?user='+txt.value,true);//2.填写地址 (请求方式,url地址+字段,同步true/异步false)
xhr.send();//3.发送
xhr.onload = function(){//4.等待服务器响应
    let data = JSON.parse(xhr.responseText)//5.接收到数据,处理数据
};

/*原生的 fetch 方式    post*/
fetch('请求地址',{   //    '请求地址' -> /xxx
    method:'post',
    headers:{
        'Content-Type':'application/x-www-form-urlencoded'
        //'Content-Type':'application/json'
    },
    body:'key=val&key2=val2'// 一定是字符串,如果不是用下面的转一下
    //body: new URLSearchParams( {a=1&b=1} ).toString()  //返回值 是搜索参数组成的字符串。
   //body: JSON.stringify({a:1, b:2, ...}) //将对象形式的参数,转成json
}).then(e=>e.json())//后端数据若不是标准JSON时,会报错,可先用e.text()得到字符串 .then(data=>{//再次.hten之后得到可以使用的数据,开始处理。 }); /*fetch get*/ fetch('/get?ren='+txt.value)//('url') .then(e=>e.json()) .then(data=>{ console.log('data'); });
例子:
    //post
    // fetch('/post',{
    //     method:'post',
    //     headers: {
    //         "Content-Type": "application/x-www-form-urlencoded"
    //     },
    //     body:new URLSearchParams({
    //         name:'aaa'
    //     }).toString()
    // })
    // .then(e=>e.text())
    // .then(e=>{
    //     console.log( eval('('+ e +')') );
    // });


    //get
    fetch('/get?name=kaiwen')
    .then(d=>{
        // console.log(d.json()); //response{}
        return d.json();
    })
    .then(d=>{
        console.log(d);
    });
    // .then(d=>{
    //     console.log(d);
    // })

    // console.dir(Object);

    // console.log(new URLSearchParams({
    //     name:'aaa',
    //     age:28
    // }).toString())

 

axios(阿克晓奥丝,爱可信)相当于封装好的请求工具

    axios.get('/get?name=kaiwen')
    .then(d=>{
        console.log(d.data);
    });

    axios.get('/get',{
        params:{
            name:'kaiwen'
        }
    })
    .then(re=>{
        console.log(re.data);
    })

    axios.post('/post',{
        name:'aaa'
    })
    .then(re=>{
        console.log(re);
    });

 

 

 

2018-12-15

原文地址:https://www.cnblogs.com/MrZhujl/p/10123800.html