【请求数据】fetch 的get请求和post请求

 fetch:

        实现ES的规范进行实现的而不是通过创建xml实现的

        fetch属于window的属性(兼容性问题)

        基于promiseAPI

        whatwg-fetch

        安装
        cnpm install whatwg-fetch -S


         get请求

       fetch("/users/login?username=123")
            .then((res)=>res.json())
            .then(data=>{
                console.log(data);
            })

        post请求
         
    fetch("/users/login",{
                method:"post"
                headers:{
                    "content-type":"application/x-www-form-urlecoded"
                }
                body:qs.stringfiy(存放post请求的时候提交的数据)
            }).then((res)=>res.json)
            .then(data=>{
                console.log(data);
            })

  

            body请求数据的格式必须是数据序列化的格式化
            
            qs模块


            {
                username:"Alley",
                age:19
            }

            username=alley&age=19

            application/x-www-form-urlencode




        fetch默认是不会携带cookie的
        所以必须设置属性credentials:include


        注意:
            fetch中第一个.then并不是成功的返回值而是一个未处理的结果集。需要根据自身的情况返回相对应
            的解析结果一般情况下我们只需要调用res.json即可(意思是返回json类型的数据)

            第二个.then中才是最终的返回结果
 
 

猜你喜欢

转载自www.cnblogs.com/yuanjili666/p/11722311.html