fetch 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的
fetch的get请求方法
简单基本的fetch请求(get)
XML/HTML代码
- <div id="app">
 - <button @click="getData">get请求</button>
 - </div>
 - <script>
 - 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的
 - new Vue({
 - // fetch
 - el:"#app",
 - methods:{
 - getData(){
 - // var p=fetch();
 - // console.log(p)//fetch方法也是promise对象
 - fetch('./data/name.json')
 - .then( (res) => { return res.json() } )//对fetch进行格式化,否则读取不到内容
 - .then( (data) => { console.log(data)} )//拿到格式化后的数据data
 - .catch(error=>console.log(error))
 - },
 - },
 - })
 
注意事项:
A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
Object --> String
B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式
XML/HTML代码
- 格式化处理的其他方式
 - fetch('./data.json')
 - .then(res=>{
 - res.json() //格式化json数据
 - //res.text()格式胡文本数据
 - //res.blob()==格式化二进制文件==
 - })
 - .then( data => console.log(data))
 - .catch( error => console.log( error ))
 
fetch的post请求方法
代码示例
XML/HTML代码
- <div id="app">
 - <button @click="postData">post请求</button>
 - </div>
 - <script>
 - new Vue({
 - // fetch
 - el:"#app",
 - methods:{
 - postData(){
 - fetch('http://10.31.161.60:8080',{
 - method:'post',
 - hearders: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 ))
 - }
 - },
 - })
 
总结
fetch要手动进行一次数据格式化,但是axios是内部进行了数据的格式化
fetch get 方法请求数据,参数要直接连接在url上
fetch 格式化数据 有三种 处理方法
.json() 格式化 json 类型数据, 将 json类型 string 转换成 json 对象
.text() 格式化文本
.blob() 格式化二进制数据
fetch 书写post请求、处理
设置请求头
通过 new URLSearchPrams 来携带参数
vue中http请求
Vue props用法详
 

 2019/08/28 13:52 | by 
  
 
 
 
 
 


