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. Sequelize框架:

    1.安装mysql支持: npm install mysql --save-dev 2.安装sequelize npm install sequelize --save-dev 3.创建ORM对象 v ...

  2. 算法Sedgewick第四版-第1章基础-025-用队列实现unix下的Directory命令

    package algorithms.util; /************************************************************************** ...

  3. 孕妇的孕周和体重对胎儿游离DNA在母体cfDNA占比的影响

    有一篇文件,研究了孕妇的孕周和体重对 胎儿游离DNA在母体cfDNA中占比的影响 文章名称:Gestational age and maternal weight effects on fetal c ...

  4. 神奇的overflow:hidden及其背后的原理

    先来看两个overflow:hidden的使用例子 1.嵌套布局内部块元素设置float:left时,导致外部元素塌方,高度为0的问题. <div class="wrap"& ...

  5. 20169219《Linux内核原理与分析》第十一周作业

    设备与模块 关于设备驱动和设备管理的四种内核成分: 设备类型:为了统一普通设备的操作所采用的分类. 模块:用于按需加载和卸载目标码的机制. 内核对象:内核数据结构中支持面向对象的简单操作,还支持维护对 ...

  6. [译]Javascript中的数列

    本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...

  7. javax.servlet.ServletConfig接口(五)

    主要作用是保存web.xml文件里面的配置信息 一个servlet对应一个ServletConfig,100个servlet对应100个ServletConfig.   代码如下(单个获取和获取所有) ...

  8. c#继承、多重继承

    c#类 1.c#类的继承 在现有类(基类.父类)上建立新类(派生类.子类)的处理过程称为继承.派生类能自动获得基类的除了构造函数和析构函数以外的所有成员,可以在派生类中添加新的属性和方法扩展其功能.继 ...

  9. ASP.NET MVC Razor语法及实例

    1.混合HTML与Razor脚本 知识点:(1).cshtml怎样引用访问数据, (2).if  for 与html嵌套 @using System.Data @using CIIC.TCP.Enti ...

  10. nodejs nodejs的操作

    nodejs的操作 由于版本造成的命令不能正常安装,请参考五问题 一.概念: 参考百度百科: http://baike.baidu.com/link?url=aUrGlI8Sf20M_YGk8mh-- ...