Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
1、使用npm
npm install axios --save
2、引用axios
import axios from "axios";
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
4.基本用法
get方法
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post方法
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
5.axios API
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(res=>{
console.log(res)
});
// 发送 GET 请求(默认的方法)
axios('/user/12345').then(res=>{
console.log(res)
});
更多详细参考文档https://www.kancloud.cn/yunye/axios/234845
6.vue中方法封装 创建文件http.js
import axios from "axios";
export default {
ajaxGet (api, cb) {
axios.get(api)
.then(cb)
.catch(err => {
console.log(err);
})
},
ajaxPost (api, sendData, cb) {
axios.post(api, sendData)
.then(cb)
.catch(err => {
console.log(err);
})
},
7、axios引用到 .vue 文件
import http from './../common/js/http'
get请求:
http.ajaxGet(url, res => {
console.log(res)
});
post请求:
http.ajaxPost(url, sendData, res => {
console.log(res)
});