我们在项目搭建好之后,需要请求api获取数据,那么最好的的方法就是用axios,那么axios怎么优雅的使用呢?请继续阅读。
1、安装
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
如果项目中已经安装了axios,那么可以忽略第1步
2、封装
项目文件配置路径
1、在config文件中配置基础url
// config.js文件内容
let config = {
apiSite: 'ace.she.dev2.zanservice.com/api'
}
const http = process.env.NODE_ENV === 'development' ? 'http' : 'https'
// const http = 'http'/ 'https' 确定是http 或者 https
export const apiRoot = `${
http}://${
config.apiSite}`
export const zanTokenHeaderName = 'X-Ca-ZanToken'
// 以上配置可以继续增加
2、在utils.js 文件配置了错误提示
import {
Notification } from 'element-ui'
// 这里引用了element-ui 组件中的提示组件,如不需要可自行写样式。
export function prompt (message) {
Notification.error({
message,
duration: 0