axios 用例
为了在CommonJS中使用require()导入时获得TypeScript类型推断(智能感知/自动完成),请使用以下方法:
const axios = require('axios').default;
// axios.<method> 能够提供自动完成和参数类型推断功能
GET 请求
发起一个 GET 请求:
const axios = require('axios');
// 在vue中引用如下:
import axios from 'axios'
// 向给定ID的用户发起请求
// 向给定ID的用户发起请求
axios.get('/user?ID=12345')
.then (function (response) {
// 处理成功情况
console.log(response);
})
.catch (function (error) {
// 处理错误情况
console.log(error);
})
.then (function () {
// 总是会执行
});
上述请求也可以按以下方式完成(可选)
// 在vue中引用如下:
import axios from 'axios'
axios.get('/user', {
params: {
ID : 12345
}
})
.then (function (response) {
console.log(response);
})
.catch (function (error) {
console.log(error);
})
.then (function () {
// 总是会执行
});
支持async/ await用法
import axios from 'axios'
async function getUser() {
try {
const response = await axios.get ('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
注意:由于async/await是ECMAScript 2017中的一部分,而且在 IE 和一些旧的浏览器中不支持,所以使用时务必要小心。
POST 请求
发起一个 POST 请求
import axios from 'axios'
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
多个并发请求
import axios from 'axios' functiongetUserAccount() { return axios.get ('/user/12345'); } functiongetUserPermissions() { return axios.get ('/user/12345/permissions'); } Promise.all([getUserAccount() ,getUserPermissions() ]) .then(function (results) { const acct = results[0]; const perm = results[1]; });
vue3 安装及使用 axios
安装axios
npm install axios
Vue3配置axios跨域实现过程解析
//vue3 根目录下 vue.config.js文件
module.exports = {
devServer: {
proxy: {
'/api/': {
target : 'https://www.test.com/', //接口域名
changeOrigin: true, //是否跨域
ws: true, //是否代理 websockets
secure: true, //是否 https 接口
pathRewrite: { //路径重置
'^/api': ''
}
}
}
}
};
将api接口放入请求的 url 中
<template>
<div>
<H1>TEST</H1>
<p>{{data}}</p>
</div>
</template>
<script>
import axis from 'axios';
export default {
name: 'Test',
data() {
return {
data: {},
};
},
methods: {
getData() {
axis.get('/api/xhr/search/queryHotKeyWord.json') //axis后面的.get可以省略
.then(
(response) => {
console.log(response);
this.data = response;
})
.catch(
(error) => {
console.log(error);
});
},
},
mounted() {
this.getData();
},
};
</script>
<style scoped>
</style>
