Vue2搭建基础架构(4)--- 使用axios
- 说明
- 官方文档
- 安装axios
- 安装命令
- 使用axios
- 测试参数以对象形式传参
- 测试参数在url地址后面拼接传参
说明
这里记录下自己在Vue2的项目使用axios请求后端接口的过程,方便以后直接使用。这里承接自己的博客Vue2搭建基础架构(3)— 使用dayjs这篇博客,在该博客项目的基础上增加使用axios。
官方文档
axios官方文档:http://axios-js.com/zh-cn/docs/
安装axios
根据官网给的命令
安装命令
npm install axios --save
在webstorm里面的Terminal输入npm install axios --save命令安装该依赖。执行完如下:
package.json会增加axios版本号
使用axios
在src目录下的utils文件夹创建一个request.js文件。request.js该代码只是一个示例代码,需要根据自己的项目需要做实际调整,代码如下:
//引入axios请求
import axios from 'axios'
//引入element-ui里面的消息提示
import { Message } from 'element-ui'const BASE_API=""
// 创建axios实例
const service = axios.create({baseURL: BASE_API, // 所有的请求地址前缀部分(没有后端请求不用写)timeout: 10 * 60 * 1000, // 请求超时时间,这里设置为10分钟withCredentials: true, //允许跨域携带凭证(cookie)credentials: true, //后端允许跨域携带cookieheaders: {//请求头设置后端需要的传参类型'Content-Type': 'application/json; charset=utf-8'}
})// request拦截器
service.interceptors.request.use(config => {// 这里可以在请求头中配置token,根据自己的项目需要自行配置return config
}, error => {// 错误日志打印Promise.reject(error)
})// response拦截器
service.interceptors.response.use(response => {//对数据返回做什么,可以可以获取到接口的code状态码,根据不同的状态码来处理不同的逻辑return response.data},error => {console.log('err' + error)Message({message: error.message,type: 'error',duration: 3 * 1000})return Promise.reject(error)}
)export default service
在src目录下创建一个api文件夹,用来存放每个模块的接口请求,假设有一个登录页面模块,那就把这个登录页面的接口都写到这个js文件里面即可,如下:
login.js代码如下:
import request from '@/utils/request'//示例以application/json格式传参
export function login(data) {return request({url: '/admin/login',method: 'post',data: data})
}//示例在url后面拼接参数传参
export function test(params) {return request({url: '/admin/login',method: 'post',params: params})
}
测试参数以对象形式传参
在HelloWorld.vue代码中修改为如下:
代码如下:
<template><div class="hello"><el-button>默认按钮</el-button><el-button type="primary">主要按钮</el-button><el-button type="success">成功按钮</el-button></div>
</template><script>
import {login} from '@/api/login'export default {name: 'HelloWorld',mounted() {// 接口请求发送示例let param={username:"admin",password:"123456"}login(param).then(res=>{console.info("请求成功",res)}).catch(error =>{console.info("请求失败",error)})}
}
</script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {margin: 40px 0 0;
}
ul {list-style-type: none;padding: 0;
}
li {display: inline-block;margin: 0 10px;
}
a {color: #42b983;
}
</style>
浏览器接口请求效果:
参数也是对象也是正确的:
控制台会报错正常。说明axios是可以正常使用的。
测试参数在url地址后面拼接传参
将login改为test方法即可
浏览器接口如下:
参数在url后面正常拼接,没有问题。
到这里axios使用示例就结束了,只需要根据具体的项目在request.js增加对应的接口认证就能正常调用接口。