接口调用fetch

接口调用fetch

fetch基本用法

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

fetch请求参数

  1. 常用配置选项

    • method(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. POST请求方式的参数传递

    fetch('/login',{
        method: 'post',
        body: 'uname=admin&pwd=123',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        console.log(ret);
    });
    //--------------------json-------------------
    fetch('/login',{
        method: 'post',
        body: JSON.stringify({
            uname:'admin',
            pwd:123
        }),
        headers:{
            'Content-Type':'application/json'
        }
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        console.log(ret);
    });
    
  3. fetch响应结果

    响应格式

    • text(): 将返回体处理成字符型
    • json():返回结果和JSON.parse(responseText)一样
    fetch('/list').then(data=>{
        return data.json();
    }).then(ret=>{
        console.log(ret);
    });
    
posted @ 2020-11-29 11:46  Maple_XL  阅读(169)  评论(0编辑  收藏  举报