您的位置:首页 > Web前端

前端框架级之数据请求的axios和fetch用法

2019-06-21 21:47 696 查看

前端框架级之数据请求的axios和fetch用法

此之前,看到了Vue,了解到了前端的3种框架级的数据请求方法:

  1. axios(第三方库)

  2. fetch(js原生)

  3. Vue.resource(这是Vue自己封装使用的类库,但比较久以前,其作者就已经放弃更新了,Vue.resource的用法和axios相似度很高 >90%,Vue2.0基本上用的都是前两者了,Vue.resource有jsonp的用法,前两者没有)。

    axios:

    axios在引入CDN之后就会暴露一个axios的全局对象

      axios的get方法:
    //A: 无参数
    axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))
    //B: 有参数
    axios({
    url: 'http://xxx',
    method: 'get' //默认就是get,可以省略,
    params: {
    key: value
    }
    })
    • axios的post方法:

    • 注意: axios中post请求如果你直接使用npmjs.com官网文档, 有问题

      ​ 解决步骤:

      ​ 1. 先设置请求头

      ​ 2. 实例化 URLSearchParams的构造器函数得到 params对象

      ​ 3. 使用params对象身上的append方法进行数据的传参

    • // 统一设置请求头
      axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
      let params = new URLSearchParams()
      
      // params.append(key,value)
      
      params.append('a',1)
      params.append('b',2)
      
      axios({
      url: 'http://localhost/post.php',
      method: 'post',
      data: params,
      headers: {  //单个请求设置请求头
      'Content-Type': "application/x-www-form-urlencoded"
      }
      })
      .then(res => {
      console.log( res )
      })
      .catch( error => {
      if( error ){
      throw error
      }
      })

fetch:

fetch是原生javascript提供的 , 所以它 可以当做全局变量使用 ,它是挂载在window对象身上的。

​ get方法:

注意事项:

​ A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将

​ Object --> String

​ B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据

fetch('http://localhost/get.php?a=1&b=2')
.then(res=> res.text()) // 先要进行数据格式化 res.json() res.blob()
.then(data => {
console.log( data )//这里才是格式化后的数据
})
.catch(error => {
if( error ){
throw error
}
})

post方法:

fetch( 'http://localhost/post.php',{
method: 'post',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}),
body: new URLSearchParams([["a", 1],["b", 2]]).toString()
})
.then( res => res.text() )
.then( data => console.log( data ))
.catch( error => console.log( error ))
}

post详情方法可以参考:

1、https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#进行_fetch_请求

2、https://blog.csdn.net/hefeng6500/article/details/81456975

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: