Axios发送get、post请求,获取并处理返回值

(97) 2024-06-05 13:01:01

一:axios是什么。
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
二:axios特点。
1.从浏览器中创建 XMLHttpRequests
2. 从 node.js 创建 http 请求
3. 支持 Promise API
4. 拦截请求和响应 (就是有interceptor)
5. 转换请求数据和响应数据
6. 取消请求
7. 自动转换 JSON 数据
8. 客户端支持防御 XSRF
三:安装配置。
1,使用 npm(当大量使用axios时,可以将axios作为vue的插件全局使用):
$ npm install axios
2,使用 cdn:

在script标签中引入:https://unpkg.com/axios/dist/axios.min.js

3,.在main.js中引入文件

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

axios.defaults.baseURL='/api'

四:get请求方法。
方法一:

axios.get('/user?ID=0909')
  .then(function (response) { 
   
    console.log(response);
  }).catch(function (error) { 
   
    console.log(error);
  });

方法二:

axios.get('/user', { 
   
    params: { 
   
      ID: 0909
    }
  }).then(function (response) { 
   
    console.log(response);
  }).catch(function (error) { 
   
    console.log(error);
  });

五;post请求方法。

axios.post('/user', { 
   
    firstName: 'frist',
    lastName: 'last'
  })
  .then(function (response) { 
   
    console.log(response);
  })
  .catch(function (error) { 
   
    console.log(error);
  });

六:在生命周期mounted里发起请求。

mounted(){ 
   
	//get
	this.axios.get('url').then(res => { 
   
		console.log('success')   //调用成功
	},res => { 
   
		console.log('error')   //调用失败
	})
	//post
	this.axios.post('url').then(res => { 
   
		console.log('success')   //调用成功
	},res => { 
   
		console.log('error')   //调用失败
	})
}

实例:

<template>
<div>
    <div class="topAll">
        <div class="detailsTop">
            <img :src="main.image">
        </div>
        <div class="detailstitle">
            { 
   { 
   main.title}}
            <div class="subTitle">{ 
   { 
   main.image_source}}</div>
        </div>
        <div v-html="main.body" class="dParagraph"></div>
    </div>
</div>
</template>

<script>
export default { 
   
    data() { 
   
        return { 
   
            main:''
        }
    },
    mounted:function(){ 
   
        this.axios.get('news/3892357').then(res => { 
   
            this.main = res.data
        })
    }
}
</script>
THE END

发表回复