• vue基础4——fetch&axios


    1. fetch

    why:
    XMLHttpRequest 是一个设计粗糙的 API,配置和调用方式非常混乱,
    而且基于事件的异步模型写起来不友好。
    兼容性不好
    get
     
    //fetch get
    fetch("json/test.json?name=kerwin&age=100").then(res=>{
    // console.log(res.json())
    //拿到的是 状态码
    // return a.text() // 文本格式
      return res.json() //json格式
    }).then(res=>{
       console.log(res.data.films)
       this.datalist = res.data.films
    }).catch(err=>{
         console.log(err)
    })
    

    post-1  

    form 编码 ,name=kerwin&age=100
    fetch("json/test.json",{
           method:"post",
           headers:{
                    "Content‐Type": "application/x‐www‐form‐urlencoded"
            },
            body:"name=kerwin&age=100" //请求体
      }).then(res=>res.json()).then(res=>{
                            console.log(res)
      })
    

    post-2  

    json 编码 ,"{name:'kerwin',age:100}"
    fetch("json/test.json",{
               method:"post",
               headers:{
               "Content-Type":"application/json"
             },
              body:JSON.stringify({
                  name:"kerwin",
                  age:100
             }) //请求体
    }).then(res=>res.json()).then(res=>{
           console.log(res)
    }) 
    
    注意:
    Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials:'include'})
    fetch("**",{
        credentials:"include",
        method:'post',
        headers: {
        "Content‐Type": "application/x‐www‐form‐urlencoded"
        },
    body: "name=kerwin&age=100",
    
    }).then(res=>res.json()).then(res=>{console.log(res)});
    

    2. axios

    https://github.com/axios/axios

    axios.get("json/test.json?name=kerwin&age=100").then(res=>{
           // res.data 才是真正的后端数据
          console.log(res.data.data.films)
          this.datalist=  res.data.data.films
    })
    

      

    post -1- x-www-form-urlencode
    axios.post("json/test.json","name=kerwin&age=100").then(res=>{
        console.log(res.data)
    })
    

      

    post -2- application/json
    axios.post("json/test.json",{
        name:"kerwin",
        age:100
    }).then(res=>{
    console.log(res.data)
    })
    
  • 相关阅读:
    图论
    城市吸引力指数
    bzoj3529(莫比乌斯反演+离线+树状数组)
    强制关闭tomcat
    bzoj2154(莫比乌斯反演)
    等差数列求和模板
    联想的显示屏校准(困难)
    bzoj2301(莫比乌斯反演)
    莫比乌斯反演模版
    菜鸟物流的运输网络(网络流)
  • 原文地址:https://www.cnblogs.com/wuziqiang/p/13278533.html
Copyright © 2020-2023  润新知