1、接口统一管理
当某个请求在多个组件中都需要发送时,可以在src/api/index.js中:进行接口统一管理。这样在接口路径发生改变时,只需要在src/api/index.js中修改对应接口,不需要找到组件中发请求的地方一个一个修改。
// 当前这个模块:api进行统一管理。
import requests from "./request";
// 三级联动接口 : /api/product/getBaseCategoryList 、 get 、无参数
export const reqCategoryList = () => {
// 发请求:axios发请求返回结果是Promise对象
return requests({url:'/product/getBaseCategoryList', method: 'get'});
}
在组件里引入、发送"reqCategoryList"请求:
// 引入"reqCategoryList"请求
import {reqCategoryList} from '@/api';
// 使用"reqCategoryList"请求
reqCategoryList();
请求返回的结果是一个Promise对象,可以通过async/await处理。
2、proxy代理--解决跨域
什么是跨域:协议、域名、端口号不同请求,称之为跨域。
比如:前端项目本地服务器(http://localhost:8080/#/home)、后台服务器(http://gmall-h5-api.atguigu.cn )
解决跨域的方案:JSONP、CROS、代理服务器。
在vue项目中通过proxy代理解决,在vue.config.js配置文件中配置以下内容:
// 代理跨域
devServer: {
proxy: {
'/api': {
target: 'http://gmall-h5-api.atguigu.cn',
// pathRewrite: {'^/api': .''.},
},
}
}