封装axios可以更好的维护请求地址改变后更好修改下面上代码
1.在src目录下创建一个文件夹建议起名utils
2.如上图所示创建三个js文件我们先来写http.js的内容
import axios from "axios";
const http=axios.create({
baseURL:'/api',
withCredentials:true,
timeout:5000
})
http.interceptors.request.use(config => {
config.headers.mytoken = 'nihao'
return config
}, err => {
console.log(err)
})
http.interceptors.response.use(res => {
return res = res.data
}, err => {
console.log(err)
})
export default http
3.现在我们写api.js的内容
import api from "./http";
export default function requests({method='get',url='',data={},params={}}){
return api({
method,
url,
data,
params
})
}
4.最后一个是统一管理请求的js文件
import req from './api'
export const gethome=()=>req({url:'home/shejishi'})
5.在页面引入gethome获取数据
<script>
import { gethome } from "../utils/req";
export default {
name: "Home",
mounted() {
gethome().then(res=>{
console.log(res);
})
},
components: {},
};
</script>