You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3多子目录路由下后端请求错误携带路由路径问题

问题解决:axios请求路径错误携带路由前缀

这是因为你用了相对路径发起axios请求,而非绝对路径导致的:

  • 当页面处于/recipes/add或/recipes/edit/:id这类嵌套路由时,当前页面的URL基准是http://localhost:7000/recipes/xxx
  • 不带开头斜杠的'api/categories'会被浏览器解析为相对于当前页面路径的相对地址,最终拼接成错误的http://localhost:7000/recipes/api/categories
  • 首页(/)的请求能正常工作,是因为根路径下的相对路径会直接从域名根目录开始拼接

解决方案1:修改请求路径为绝对路径

直接给请求路径加上开头的斜杠,强制从域名根目录开始拼接:

// 原错误写法
// state.allCategories = (await axios.get('api/categories')).data;

// 修改后
state.allCategories = (await axios.get('/api/categories')).data;

解决方案2:全局配置axios baseURL(推荐)

在项目入口文件(比如main.js)中配置axios的基础路径,后续请求无需重复写前缀:

import axios from 'axios';

// 设置全局基础请求路径
axios.defaults.baseURL = '/api';

之后发起请求时只需写接口的后半段:

// 自动拼接为 '/api/categories'
state.allCategories = (await axios.get('categories')).data;

内容的提问来源于stack exchange,提问作者Damon Cost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 15:27:14