需求:
一般用脚手架创建的项目都会在很多地方用到后端给的数据,后端给了很多接口的情况下,我们就可以封装一下全局的网络,对后端的接口统一下,方便我们的使用和后续对该接口的继续调用。
首先,我们先确定axios是否已经安装成功
然后,我们先创建一个js文件,例如:utils.js文件,在此文件对网络做初始封装
import axios from "axios";
export function request(config) {
const instance = axios.create({
// 设置请求头
baseURL: 'https://api.shop.eduwork.cn',
// 设置请求时间
timeout: 5000
})
// 请求拦截
instance.interceptors.request.use(config => {
// 如果有一些接口需要认证才可以访问,就在这统一设置
// 例如登录的token
//怎么依靠token做请求拦截?可移步
https://blog.csdn.net/weixin_61285710/article/details/122626785?spm=1001.2014.3001.5502
// 直接放行
return config;
},error => {
})
// 响应拦截
instance.interceptors.response.use(res => {
return res;
},error => {
// 如果有需要授权才可以访问的接口,统一去login授权
// 如果有错误,这里面去设置处理,显示错误信息
})
return instance(config);
}
接下来,我们可以用一个单独的文件放所有的接口,例如 user.js文件
// 导入封装的全局网络
import {request} from "./utils";
// 给单独的URL封装的函数
export function getHomeAllDate(data){
return request({
url: '/api/index',
method: 'post' // 请求格式也可以写在util.js文件里
data,
})
}
最后,就是我们需要引用该接口的组件引用就可以了
<script>
import { getHomeAllDate} from '@/user.js'
export default {
name: 'Home',
mounted(){
getHomeAllDate().then(res => {
console.log('接口调用成功')
})
}
}
<script>
封装好了网络,不知怎么判断是否登录?可移步
(47条消息) 登录验证,未登录时跳转登录页面,登录了直接跳转相应页面(vue)(vue-router)_秃秃秃了的博客-CSDN博客https://blog.csdn.net/weixin_61285710/article/details/122626479?spm=1001.2014.3001.5501