安装axios

npm install axios -S

创建相关目录文件

image.png

request.js配置

  1. import axios from 'axios'
  2. export function request(config) {
  3. // 创建axios的实例
  4. const instance = axios.create({
  5. baseURL: 'https://api.shop.eduwork.cn',
  6. timeout: 10000
  7. })
  8. // 请求拦截器配置
  9. instance.interceptors.request.use(config => {
  10. // config.headers.Authorization = window.sessionStorage.getItem('token')
  11. return config
  12. }, error => {
  13. console.log(error)
  14. return Promise.error(error)
  15. }
  16. )
  17. // 响应拦截器配置
  18. instance.interceptors.response.use(response => {
  19. console.log(response)
  20. return response.data
  21. }, error => {
  22. switch (error.response.status) {
  23. case 401:
  24. console.log("无权访问")
  25. break
  26. case 403:
  27. console.log("token过期啦")
  28. break
  29. case 404:
  30. console.log("404啦")
  31. break
  32. default:
  33. return Promise.reject(error)
  34. }
  35. return Promise.reject(error)
  36. })
  37. // 发送真正的网络请求
  38. return instance(config);
  39. }
  40. export default request

http.js配置

  1. import {request} from './request'
  2. const http = {
  3. get(url, params) {
  4. const config = {
  5. method: 'get',
  6. url: url
  7. }
  8. if (params) config.params = params
  9. return request(config)
  10. },
  11. post(url, params) {
  12. const config = {
  13. method: 'post',
  14. url: url
  15. }
  16. if (params) config.data = params
  17. return request(config)
  18. },
  19. put(url, params) {
  20. const config = {
  21. method: 'put',
  22. url: url
  23. }
  24. if (params) config.params = params
  25. return request(config)
  26. },
  27. delete(url, params) {
  28. const config = {
  29. method: 'post',
  30. url: url
  31. }
  32. if (params) config.params = params
  33. return request(config)
  34. }
  35. }
  36. export default http

home.js配置

按照页面,每个页面创建一个js文件,统一管理api请求方式和地址

  1. import http from './http'
  2. export function getHomeAllData(){
  3. return http.get('/api/index')
  4. }

vue组件发起请求

  1. <template>
  2. <h1>首页</h1>
  3. </template>
  4. <script>
  5. // @ is an alias to /src
  6. import {onMounted} from 'vue'
  7. import {getHomeAllData} from '@/api/home'
  8. export default {
  9. name: 'Home',
  10. components: {},
  11. setup() {
  12. // 轮播图数据
  13. let carouselList = ref([])
  14. // 获取轮播图数据
  15. async function carouselData() {
  16. carouselList.value = await getCarousel()
  17. }
  18. onMounted(() => {
  19. carouselData()
  20. })
  21. }
  22. }
  23. </script>