首页 > 技术文章 > fetch网络请求基本用法

qiaozhiming123 2021-07-19 10:43 原文

getRequest(){

        fetch("http://127.0.0.1:8888/getReq?naem=张三",{method:"get"}).then(res=>{
            //fech第一个then方法里的参数并不是直接返回的数据,需要对该对象做序列化处理(json),再第一个then里才能拿到数据
            return res.json();
            console.log(res)
        }).then(data=>{
            console.log(data)
        }).catch(err=>{
            console.log(err)
        })

    }

    postRequest(){
        /*
        * post请求如果传递数据,数据写在第二个参数对象里的body字段里,数据类型可以是json数据格式(json.string()),也可以是querystring格式
        * */
        fetch("http://127.0.0.1:8888/postReq",{
            method:"post",
            // body:JSON.stringify({name:"张三",age:"20"})
            // body:"name=张三"
            body:qs.stringify({name:"张三",age:"20"}),
            // headers:{"Content-Type":"application/json"}
            headers:{"Content-Type":"application/x-www-from-urlencoded"}
        }).then(res=>{

            return res.json();
            console.log(res)
        }).then(data=>{
            console.log(data)
        }).catch(err=>{
            console.log(err)
        })


推荐阅读