准备后端接口
首先,我已经写好一个后端接口用来返回我的用户数据,并用Postman测试成功如下:
以我的接口为例,接口地址为:http://localhost:8080/user/selectAll
返回Json为:
{"code": "200","msg": "请求成功","date": [{"id": 1,"username": "乐乐乐","usersex": "女","userborn": "2002-03-15","useraddress": "地球","userphone": "18055985888","useremail": "123@qq.com","avatar": "assets/img/userimg.jpg","state": true,"loginID": 1},{"id": 4,"username": "nimo","usersex": "男","userborn": null,"useraddress": null,"userphone": "18058955635","useremail": null,"avatar": "assets/img/猎鹰_proc.jpg","state": false,"loginID": 0}]
}
axios基础方法
安装好axios,不会的话看一下这个文章:VS code vue 使用ElementUI和axios_vs code使用axios-CSDN博客
在需要接口数据的前端页面中加入下面的代码:
<script>
import axios from "axios"export default {data () {return {users: [] //用来装返回的数组数据}},mounted () {axios.get('http://localhost:8080/user/selectAll').then(res => {console.log(res.data)this.users = res.data.date})}
};</script>
如果控制台输出成功那么就成功了
封装进阶
还可以再进一步,对axios做一个拦截器处理,对返回的数据和请求做一个统一处理
新建一个名为request.js的文件,代码如下:
import router from "@/router"
import axios from "axios"const request = axios.create({baseURL: 'http://localhost:8080',timeout: 30000
})//response拦截器
//发送请求时统一处理,如加token
request.interceptors.request.use(config => {config.headers['Content-Type'] = 'application/json;charset=utf-8'let user = JSON.parse(localStorage.getItem("hon-admin") || '{}')config.headers['token'] = user.token//设置请求头return config
}, error => {console.error('request error: ' + error)return Promise.reject(error)
})//response拦截器
//接口响应后统一处理结果
request.interceptors.response.use(response => {let res = response.data//兼容服务端返回的字符串数据if (typeof res === 'string') {res = res ? JSON.parse(res) : res}//没有权限跳转到登录if (res.code === '401') {router.push('/login')}return res},error => {console.error('response error:' + error)return Promise.reject(error)}
)export default request
这是,前端代码为:
<script>
//引用request文件
import request from "@/utils/request"export default {data () {return {logins: []}},mounted () {request.get('/user/selectAll').then(res => {this.logins = res.dateconsole.log(this.logins)})}
};</script>
这样跟规范,代码也更加简洁