fetch

是新一代XMLHttpRequest的一种替代方案。无需安装其他库。可以在浏览器中直接提供其提供的api轻松与后台进行数据交互。

基本用法:

1 fetch(url,{parmas}).then(res=>

return res.json()  //返回promise对象

).then(data=>{

return data     //返回真正数据

}).catch(err=>{

throw new Error(err)

})

------------------------------------------------------------------------------------------------------------------

(1) get 方式:

<script src="http://cdn.bootcss.com/qs/6.5.2/qs.js"></script>  
<script type="text/javascript">

window.onload=function(){

var url="http://www.baidu.com"  //填写自己的域名地址
        var btn=document.getElementById("btn");

var data={
           verified:1, 
           warningLevel:0,
           sessionID:"3ecf8905a98cb752b127302bf08f08e5"
        }

btn.onclick=function(){

fetch(url+"/stats/getUserList?sessionID=3ecf8905a98cb752b127302bf08f08e5&verified=1&warningLevel=0").then(res=>{
                              return res.json();     //返回promise对象

}).then(data=>{

console.log("返回值:",data)

}).catch(err=>{

console.log(err)

})

}

------------------------------------------------------------------------------------------------------------------

(2) POST方式:

btn.onclick=function(){             
                      fetch(url+"/stats/getUserList",{
                           method:"POST",
                           headers:{
                                'Content-Type': 'application/x-www-form-urlencoded'
                           },
                           body:Qs.stringify(data)
                         }).then(res=>{

console.log(res)
                              return res.json();

}).then(data=>{

console.log("返回值:",data)

}).catch(err=>{

console.log(err)

})
        }

注意:1 fetch返回的是promise对象。所以fetch().then()第一个then里返回的并不是真正的数据。而是一个promise,所以我们需要通过链式操作第二个then()来获取真正的数据。

2  fetch发送参数是通过body字段来实现的。body是fetch第二个参数的必选参数之一。params的参数如下

method(String): HTTP请求方法,默认为GET
            body(String): HTTP的请求参数
            headers(Object): HTTP的请求头,默认为{}
            credentials(String): 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie

3 body带的参数是一个序列化以后的字符串。类似 name="coc"&age=30.所以这里我们通过qs库进行了序列化。注意通过cdn引入qs后qs函数应该是Qs,Qs.stringify(data)

2 在vue中的使用:

fetch支持在vue环境中使用。这样通过ajax请求就无需通过安装axios依赖库来实现。

具体使用:

(1)组件中发送请求:

<div style="margin-top:20px">
       <button @click="getLevelData" >获取黄色用户信息</button>
   </div>

export default{
         name:"users",
         data(){
             return{
           
                arr:[]
             }
         },

methods:{

getLevelData(){

async function getInfo(){
                    
                               return  await fetch(api+"/stats/getUserList",{
                                              method:"post",
                                              headers:{
                                                  'Content-Type':"application/x-www-form-urlencoded"
                                               },
                                               body:qs.stringify(data)
                                 }).then(res=>res.json())

}
                      getInfo().then(res=>{

this.arr=res.data.data

}).catch(err=>{
                              console.log("get--error:",err)
                        })

}

}

(2) 表单元素通过fetch发送ajax请求

<p>手机号:<input type="text" v-model="mobile"></p>
        <p>密码:<input type="password" v-model="password"></p>
        <input type="button" value="登录" @click="go">

<script>

export default {
  
  name:"Login2",
  data(){
    return{
        mobile:"",
        password:"",
    }
  },
  methods:{

go(){
       var data={
         mobile:this.mobile,
         password:this.password
       }

getLevelData(){

async function getInfo(){
                    
                               return  await fetch(api+"/stats/getUserList",{
                                              method:"post",
                                              headers:{
                                                  'Content-Type':"application/x-www-form-urlencoded"
                                               },
                                               body:qs.stringify(data)
                                 }).then(res=>res.json())

}
                      getInfo().then(res=>{

this.arr=res.data.data

}).catch(err=>{
                              console.log("get--error:",err)
                        })

}
           }
  }
}    
</script>

注意:如果是提交表单元素,那么一定要添加headers参数, 而且content-Type的值必须是application/x-www-form-urlencoded

heders:{
                  'Content-Type':"application/x-www-form-urlencoded"
             },

(2)通过vuex请求数据

export default {
  
  name:"Login2",
  data(){
    return{
      mobile:"",
        password:"",
      val:""
    }
  },
  methods:{

go(){
       var data={
            mobile:this.mobile,
            password:this.password
       }

this.$store.dispatch("login",data).then(res=>{

this.arr=res.data.data

}).catch(err=>{
           console.log("登录;err",err)

})
      }
  }
}

store.js  中对应的action

login({commit},payload){
          
        return new Promise((resolve,reject)=>{

fetch("/account/login",payload).then(res=>{
               
                   resolve(res)

}).catch(err=>{

console.log("登录--err:",err)
                  reject(err)
                  
           })

}) 
    },
通过vuex实现请求,fetch发送请求可以不用带method,body和headers等参数
---------------------
作者:sleeppingforg
来源:CSDN
原文:https://blog.csdn.net/baidu_41601048/article/details/83413884
版权声明:本文为博主原创文章,转载请附上博文链接!

Vue 中怎么发起请求(二)的更多相关文章

  1. Vue 中怎么发起请求(一)

    1.vue 支持开发者引入 jquery 使用 $.ajax() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1.首先,在 package.json 中添加 j ...

  2. vue中比较完美请求的栗子(使用 axios 访问 API)

    vue中比较完美请求的栗子(使用 axios 访问 API) 官网地址:https://vuejs.bootcss.com/v2/cookbook/using-axios-to-consume-api ...

  3. Vue中axios有关请求头的几点小结

    在Vue前端中向后端发起http请求会有着两种写法:一种是在vue文件中直接导入axios模板,另外一种是使用Vue的属性$http. 1.在第一种方式中,在同一个工程中所添加的vue文件直接使用ax ...

  4. vue axios配置 发起请求加载loading请求结束关闭loading

    axios带有请求拦截器,避免在每个请求里面加loading重复操作,可以封装进去,在请求开始时加载loading层,请求结束关闭,loading层用vux的loading加载 axios.js im ...

  5. Vue中发送ajax请求——axios使用详解

    axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...

  6. Vue 中使用Ajax请求

    Vue 项目中常用的 2 个 ajax 库 (一)vue-resource vue 插件, 非官方库,vue1.x 使用广泛 vue-resource 的使用 在线文档   https://githu ...

  7. vue中axios 配置请求拦截功能 及请求方式如何封装

    main.js 中: import axios from '................/axios' axios.js 中: //axios.js import Vue from 'vue' i ...

  8. vue 中使用 axios 请求接口,请求会发送两次问题

    在开发项目过程中,发现在使用axios调用接口都会有两个请求,第一个请求时,看不到请求参数,也看不到请求的结果:只有第二次请求时才会有相应的请求参数以及请求结果: 那为甚么会有这么一次额外的请求呢,后 ...

  9. vue中使用vue-qrcode生成二维码

    要使用二维码,引入一个包就可以了,使用非常简单,话不多说,看代码吧 //1,引入, import VueQrcode from '@xkeshi/vue-qrcode'; Vue.component( ...

随机推荐

  1. php学习笔记-include

    这个和C语言中的include是同样的用法,如果一个php文件中有一句include a.php,那么执行的时候就会把a.php的内容插入到这个php文件中. 举个例子,我现在有一个名为hellowo ...

  2. Java中常见设计模式面试

    一.设计模式的分类 总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式.抽象工厂模式.单例模式.建造者模式.原型模式. 结构型模式,共七种:适配器模式.装饰器模式.代理模式.外观模式.桥接 ...

  3. JavaScript相关知识和经验的碎片化记录

    1.JavaScript提示“未结束的字符串常量”错误解决方法 1.1 JavaScript引用时,使用的字符语言不一致.    比如:<script type=”text/javascript ...

  4. kaggle Data Leakage

    What is Data Leakage¶ Data leakage is one of the most important issues for a data scientist to under ...

  5. mysql双机热备份的实现步骤

    MySQL 提供了数据库的同步功能,这对我们实现数据库的冗灾.备份.恢复.负载均衡等都是有极大帮助的.本文描述了常见的同步设置方法.<?xml:namespace prefix = o /> ...

  6. leetcode 6 ZigZag Converesion

    class Solution { public: string convert(string s, int nRows) { if (nRows <= 1) return s; string r ...

  7. ipa包使用命令上传fir.im或者蒲公英

    我们的工程做了自动打包处理,但是每次打完ipa后只是放置于一个共享盘或者本地,为了方便测试,每次都要手动上传上传fir或者蒲公英,比较麻烦.所以研究了一下怎么能在打完包后直接脚本上传到上传fir或者蒲 ...

  8. Glib学习笔记(一)

    你将学到什么 如何使用GObject实现一个新类 类头文件 声明一个类型的方法选择取决于类型是可被继承的还是不可被继承的. 不可被继承的类型(Final类型)使用G_DECLARE_FINAL_TYP ...

  9. Mybatis基于代理Dao实现CRUD操作 及 Mybatis的参数深入

    Mybatis基于代理Dao实现CRUD操作 使用要求: 1.持久层接口和持久层接口的映射配置必须在相同的包下 2.持久层映射配置中mapper标签的namespace属性取值必须是持久层接口的全限定 ...

  10. bsdasm

    bsdasm 来源 http://www.int80h.org/bsdasm/ Preface by G. Adam StanislavWhiz Kid Technomagic Assembly la ...