axios数据请求get、post方法的使用

154 阅读1分钟

我们常用的有get方法以及post方法,下面简单的介绍一下这两种请求方法

vue中使用axios方法我们先安装axios这个方法

npm install --save axios

安装之后

采用按需引入的方法,哪个页面需要请求数据就在哪个页面里引入一下。

import axios from 'axios'

==也可全局引入==

/*main.js*/

import axios from 'axios'

Vue.prototype.$axios = axios;

引入之后我们就可以在vue中进行数据请求了,在methods中创建一个方法

methods:{
    
    getInfo(){
        let url = "/api/login"
        axios.get(url).then((res)=>{
            console.log(res)
        }).catch(err=>{})    
    }  ,
    //方法一
    getInfo(){
        let url = "/api/login?id=123465"
        axios.get(url).then((res)=>{
            console.log(res)
        }).catch(err=>{}) 
    },
    //方法二   推荐
    getInfo(){
        let url = "/api/login"
        let 
        axios.get(url,{
            params={
                id:123456
            }
        }).then((res)=>{
            console.log(res)
        }).catch(err=>{}) 
    },
}

然后我们在mounted这个生命周期中进行调用

 mounted(){
     this.getInfo()  
 }

Post 的用法

// 提示:该方式传递的参数是json格式,如上传不成功,需检查后台接收的方式是不是application/x-www-form-urlencoded默认格式,jquery中ajax请求的就是application/x-www-form-urlencoded,后台需要body-parser解码
        Vue.axios.post('/api/post', {
          // 此参数就是写到请求体中的参数
          stuName: '盖聂',
          height: 180
        }).then((response) => {
          console.log(response);
          console.log(response.data);
          this.postData = response.data;
        }).catch((error) => {
          console.log(error);
        });