欢迎来到Srr的博客

在vue中Axios的使用总结

这个作业属于哪个课程 2021春软件工程实践S班(福州大学)
这个作业要求在哪里 软件工程实践总结&个人技术博客
这个作业的目标 个人技术总结
其他参考文献 CSDN、博客园、简书

技术概述

概述:在前后端分离编程中以vue作为前端框架时使用Axios进行前后端数据交互的使用。

技术详述

  • 安装
npm install vue-axios --save
  • 在main.js页面引用
import axios from 'axios'
Vue.prototype.$axios = axios
...
new Vue({
    el: '#app',
    axios,
    template: '<App/>'
})
...
  • 使用
      this.$axios({
        method: 'get',           //方法为get或post
        headers: {
          'Content-type': 'application/json;charset=UTF-8'
        },
        data: xxxxx,             //此处为post方法传输的数据
        url: 'xxxxx'             //此处为后端接口url
      }).then((response) => {
        ...           
      }).catch((error) => {
        console.log(error)       //请求失败返回的数据
      })
  • 流程图

遇到的问题和解决

  • axios 解决跨域cookie丢失问题
axios.defaults.withCredentials = true;
  • axios 数据赋值问题

发起请求时报如下错


axios 数据赋值应使用以下两种之一,不能混

//    const that = this
      this.$axios({
        method: 'get',           //方法为get或post
        headers: {
          'Content-type': 'application/json;charset=UTF-8'
        },
        data: xxxxx,             //此处为post方法传输的数据
        url: 'xxxxx'             //此处为后端接口url
      }).then((response) => {    //使用箭头函数
        console.log(JSON.stringify(response))       //请求成功返回的数据  
        this.forklifts = response.data.data            //将请求到的数据赋到data中
        ...            
//    }).then(function(response){    //将指向vue对象的this赋值给外部方法定义的属性,然后在内部方法中使用该属性
//      that.forklifts = response.data.data
//      ...
      }).catch((error) => {
        console.log(error)       //请求失败返回的数据
      })

总结

通过Axios进行前后端的数据交互使用起来还是非常简单和方便的,绝大部分的请求套用模板即可,遇到的跨域cookie丢失问题和数据赋值问题也顺利解决了。希望以后可以再深入一步地学习Axios的使用。

参考文献和资料

vue中axios基本用法——阳光之城alt
vue中使用axios的多种方式——谢大见
vue axios 数据(data)赋值问题

posted @ 2021-06-28 19:14  Srr  阅读(300)  评论(1编辑  收藏  举报