Vue中进行异步请求

前端的数据均是通过接口请求拿到的,而Vue本身不支持ajax请求,那么该怎么解决Vue中的异步请求呢?这儿提供了几种方法,希望对大家有所帮组。

一、axios实现异步请求

1.项目中安装axiox

npm install --save axios

2.在main.js中引入以供全局使用

import axios from 'axios'
//可以给axios的ajax请求设置统一的主机和端口号
axios.defaults.baseURL = "http://157.122.54.189:8080/";
//将axios这个对象添加到Vue的原型对象中,在使用的时候就只需要使用this.对象名就可以了
Vue.prototype.$http = axios

3.axios之get请求
vue前端:

<template>
    <div>
    </div>
</template>
<script>
export default {
  methods:{
    getData(){
        //axios-get请求
        this.$http.get('/getData1')
            .then(r => console.log(r))//接口调用成功返回的数据
            .catch(err => console.log(err)),//接口调用失败返回的数据
    }
  }
  mounted(){//模板或el对应的html渲染完成后再调用里面的方法
    this.getData()
  }
}
</script>
<style lang="scss" scoped>

</style>

node后端:

server.get('/getData1',function(req,res){
  res.send({
    'msg':'aaa'
  })
})

请求结果:
这里写图片描述
4.axios之post请求
Vue前端:
提交参数的两种形态:
// 1.可以直接传入字符串 name=张三&age=19
// 2.可以以对象的形式传入{name:”三”,age:19}

<template>
    <div>
    </div>
</template>
<script>
export default {
  methods:{
    getData(){
        //axios-post请求传值
      this.$http({
          method:"post",
          url:"/getData2",
          headers:{
              'Content-type': 'application/x-www-form-urlencoded'
          },
          data:{
              name:'xxx'
          },
          transformRequest: [function (data) {//更改传值格式
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret.slice(0,ret.length-1)
            }],
      })
        .then(r => console.log(r))
        .catch(err => console.log(err))
    }
  }
  mounted(){//模板或el对应的html渲染完成后再调用里面的方法
    this.getData()
  }
}
</script>
<style lang="scss" scoped>

</style>

node后端:

server.post('/getData2',function(req,res){
  req.on("data",function(data){
      console.log(querystring.parse(decodeURIComponent(data)));
  });
  res.send({
    'msg':'bbb'
  })
})

结果:
这里写图片描述
这里写图片描述

看到这儿,你可能会疑惑,为什么post请求这么繁琐。这和axios post方法默认使用application/json格式编码数据有关,生成的数据格式是request payload,并不是我们常用的Form data格式(表单数据格式)。使用这种编码方式,传递到后台的将是序列化后的json字符串,而不是我们想要的对象的形式,后端拿到的值则用原有的解析方式无法解析,则会解析出错误的数据。故而,这里前端可以现将其转化一下,转化成键值对的形式再传给后端,后端再稍作处理就可以正常使用。
当然,也可以后端去做出解决,而且解决方式更加简单一些,针对Node直接将传过来的json字符串用body-parser中间件进行解析就好。

server.post('/getData2',bodyParser.json(),function(req,res){
    console.log(req.body);
    res.send({
      'msg':'bbb'
    })
});

二、vue-resource实现异步请求(和axios步骤基本相同)

1.项目中安装vue-resource

npm install --save vue-resource

2.在main.js中引入以供全局使用

import vueResource from 'vue-resource'
Vue.use(vueResource)//这儿有所不同

3.vue-resource之get请求

this.$http.get('/getData1')
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

4.vue-resource之post请求

this.$http.post('/getData2',{name:"bbb"})
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

5.vue-resource之jsonp请求

this.$http.jsonp('/getData3')
    .then(r => console.log(r))//接口调用成功返回的数据
    .catch(err => console.log(err)),//接口调用失败返回的数据

猜你喜欢

转载自blog.csdn.net/weixin_40970987/article/details/82460441