Vue中使用axios

导读:本篇文章讲解 Vue中使用axios,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、axios

        axios是一个基于Promise的网络请求库。既可以在node.js(服务器端)使用,也可以在浏览器端使用

        1. 在node.js中使用的原生的http模块

        2. 在浏览器中使用的XMLHttpRequest

二、vue中的使用方法

        1. 安装:npm install axios

        2. 引用方法

​         A、原生的方式(不推荐使用)

axios({
      url: 'http://localhost:8055/students/test',  //远程服务器的url
      method: 'get' //请求方式
    }).then(res=>{
      this.students = res.data
    }).catch(e=>{
      console.log(e)
    })
//缺点:每个使用axios的组件都需要导入

        强调:axios对服务器端数据的封装

  • ​ res.config:响应信息的配置情况
  • ​ res.data:响应的数据
  • ​ res.headers:响应头信息(信息的大小、信息的类型)
  • ​ res.request:异步的请求对象(XMLHttpRequest)
  • ​ res.status:请求-响应的状态码(200)
  • ​ res.statusText:请求-响应状态码对应的文本信息

​         B、在项目的main.js文件中导入axios,将其写入Vue的原型中(推荐使用)

import axios from "axios";
Vue.prototype.$http = axios //在Vue的原型上添加一个$http属性,该属性保存了axios
axios.defaults.baseURL = 'http://localhost:8055'

        在组件中通过this.$http的方式来使用

this.$http.get('http://localhost:8055/students/test').then(res=>{
          this.students = res.data
}).catch(e=>{
          console.log(e)
})

        缺点:只能在vue2中使用,vue3中不能用

        C、将axios单独封装到某个配置文件中(在配置文件中单独封装axios实例)—— (推荐使用)

//配置文件:axiosapi.js
import axios from "axios";
const axiosapi = axios.create({
    baseURL: 'http://localhost:8055', //基础的地址
    timeout: 2000  //连接超时的时间(单位是毫秒)
})
export default  axiosapi  //axiosapi是axios的实例
import $http  from '../config/axiosApi'  //$http是可变的
$http.get('/students/test').then(res=>{
          this.students = res.data
}).catch(e=>{
          console.log(e)
})

        优点:既可以在Vue2中使用,也可以在Vue3中使用

三、axios中不同请求方式向服务器提交数据的格式

        1. get方式请求:服务器端通过 req.query.参数名 来接收

        ​ 第一种:直接将请求参数绑在url地址上。

Vue中使用axios

         第二种:通过params方式进行提交

Vue中使用axios

    console.log('Get请求的参数:',req.query.userName),

        2. post方式请求:服务器端通过 req.body.参数名 来接收

Vue中使用axios

    console.log('Post请求的参数:',req.body.userName),

        3. put方式请求:和post方式一样

​        4. delete方式请求:和get方式一样

四、实例

​        axios端

//StudentInfo.vue

<template>
  <div>
    <table border="1" align="center">
      <thead>
      <tr>
        <th width="100">学号</th>
        <th width="100">姓名</th>
        <th width="100">性别</th>
        <th width="100">地址</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item,index) in students" :key= 'index' >
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.sex}}</td>
        <td>{{item.address}}</td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
// 第一种方式
// import axios from 'axios';

//第三种方式
import $http from '../axiosApi' //$http是可变的

export default {
  name: "StudentInfo",
  data(){
    return{
      students:[]
    }
  },
  methods:{
    getStudents(){
      // 第一种方式
      // axios({
      //   url:'http://localhost:8055/students/test',//远程服务器的url
      //   methods:'get'//请求方式
      // }).then(res=>{
      //   console.log(res)
      //   this.students = res.data
      // }).catch(e=>{
      //   console.log(e)
      // })

      //第二种方式
      // this.$http.get('http://localhost:8055/students/test').then(res=>{
      //   this.students = res.data
      // }).catch(e=>{
      //   console.log(e)
      // })

      //第三种方式
      let str = '小乔'
      $http.delete('/students/test',{
          params:{
             userName:str
          }
      }).then(res=>{
        this.students = res.data
      }).catch(e=>{
        console.log(e)
      })
    }
  },
  created() {
    this.getStudents()
    // this.student = [
    //   {id:1001,name:'试试',sex:'男',address:'西安'}
    // ]
  }
}
</script>

<style scoped>

</style>
//App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
<!--    <HelloWorld msg="Welcome to Your Vue.js App"/>-->
    <StudentInfo/>
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'
import StudentInfo from "@/components/StudentInfo";
export default {
  name: 'App',
  components: {
    // HelloWorld
    StudentInfo
  }
}
</script>
//main.js

import Vue from 'vue'
import App from './App.vue'
// import axios from 'axios';

// Vue.config.productionTip = false
// Vue.prototype.$http = axios //在Vue的原型上添加一个$http属性,该属性保存了axios
new Vue({
  render: h => h(App),
}).$mount('#app')
//axiosApi.js

import axios from 'axios';
const axiosapi = axios.create({
    baseURL:'http://localhost:8055',//基础的地址
    timoout:2000 //连接超时的时间(单位是毫秒)
})

export  default axiosapi

        服务器端:

//studentApi.js

var express = require('express');
var router = express.Router();

/* http://localhost:8055/students/test*/
router.delete('/test', (req,res)=>{
    let arr = [
        {id:1001,name:'刘备',sex:'男',address:'野区'},
        {id:1002,name:'周瑜',sex:'男',address:'中路'},
        {id:1003,name:'吕布',sex:'男',address:'上路'},
        {id:1004,name:'大乔',sex:'女',address:'辅助'},
        {id:1005,name:'孙尚香',sex:'女',address:'下路'},
    ]
    console.log('Delete请求的参数:',req.query.userName),
    res.json(arr)
});

module.exports = router;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/79741.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!