vue中 fetch跨域请求

| |
[不指定 2019/08/28 13:52 | by 刘新修 ]

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

fetch的get请求方法

简单基本的fetch请求(get)

XML/HTML代码
  1. <div id="app">  
  2.     <button @click="getData">get请求</button>  
  3. </div>  
  4.   
  5.   
  6.   
  7. <script>  
  8. 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的  
  9. new Vue({  
  10.     // fetch   
  11.     el:"#app",  
  12.     methods:{  
  13.            getData(){  
  14.         // var p=fetch();  
  15.         // console.log(p)//fetch方法也是promise对象  
  16.         fetch('./data/name.json')  
  17.         .then( (res) => {  return res.json() } )//对fetch进行格式化,否则读取不到内容  
  18.         .then( (data) => { console.log(data)} )//拿到格式化后的数据data  
  19.         .catch(error=>console.log(error))  
  20.          },  
  21.   
  22.     },  
  23. })   

注意事项:


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

  Object --> String

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

XML/HTML代码
  1. 格式化处理的其他方式  
  2. fetch('./data.json')  
  3. .then(res=>{  
  4.     res.json() //格式化json数据  
  5.     //res.text()格式胡文本数据   
  6.     //res.blob()==格式化二进制文件==  
  7. })  
  8. .then( data => console.log(data))  
  9. .catch( error => console.log( error ))  

fetch的post请求方法
代码示例

XML/HTML代码
  1. <div id="app">  
  2.     <button @click="postData">post请求</button>  
  3. </div>  
  4.   
  5.   
  6. <script>  
  7. new Vue({  
  8.     // fetch   
  9.     el:"#app",  
  10.     methods:{  
  11.         postData(){  
  12.             fetch('http://10.31.161.60:8080',{  
  13.                 method:'post',  
  14.                 hearders:new Headers({  
  15.                     //设置请求头,解决跨域问题   
  16.                     'Content-Type':'application/x-www-form-urlencoded'  
  17.                 }),  
  18.                 //解决请求数据类型限制的问题  
  19.                 // body:new URLSearchParams([["a", 1],["b", 2]]).toString()  
  20.             })  
  21.             .then( res => res.text() )  
  22.             .then( data => console.log( data ))  
  23.             .catch( error => console.log( error ))  
  24.   
  25.         }  
  26.     },  
  27. })  

总结

fetch要手动进行一次数据格式化,但是axios是内部进行了数据的格式化

fetch get 方法请求数据,参数要直接连接在url上

fetch 格式化数据 有三种 处理方法

.json() 格式化 json 类型数据, 将 json类型 string 转换成 json 对象

.text() 格式化文本

.blob() 格式化二进制数据

fetch 书写post请求、处理

设置请求头

通过 new URLSearchPrams 来携带参数

H5/JS/CSS | 评论(0) | 引用(0) | 阅读(3922)