如何在Axios请求中提取并使用当前URL中的路径参数
从当前页面URL提取末尾数字拼接Axios请求地址的实现方案
分两种项目常见场景给出可直接复用的代码:
场景1:项目已接入前端路由(React Router / Vue Router 等动态路由方案)
这种场景不需要手动解析浏览器原生URL,直接通过路由内置能力获取动态参数即可,准确率最高。
- React Router v6 写法:
import { useParams } from 'react-router-dom' const getProd = () => { // 从路由配置的动态参数:id中直接拿到URL末尾的数值 const { id } = useParams() axios.get(`http://localhost:3000/customer/product/${id}`) .then((result) => { setProducts(result.data) }) } - Vue Router 写法(组合式API):
import { useRoute } from 'vue-router' const getProd = () => { const route = useRoute() // 直接拿到路由匹配到的动态id值 axios.get(`http://localhost:3000/customer/product/${route.params.id}`) .then((result) => { setProducts(result.data) }) }
场景2:未接入前端路由,纯原生页面逻辑
直接基于浏览器原生window.location对象解析路径即可,不需要额外引入依赖:
const getProd = () => { // 拆分当前页面路径,过滤掉空字符串片段 const pathList = window.location.pathname.split('/').filter(Boolean) // 取路径最后一段转成数字,匹配你要的URL末尾参数值 const productId = Number(pathList[pathList.length - 1]) // 简单校验避免非数字值发无效请求 if (Number.isNaN(productId)) return axios.get(`http://localhost:3000/customer/product/${productId}`) .then((result) => { setProducts(result.data) }) }
开发提示:写提取逻辑时不要硬编码路径段的固定下标,比如写死取拆分后数组的第2项,后续如果路由加了前缀层级会直接导致逻辑失效,取最后一段的写法适配性更强。
内容的提问来源于stack exchange,提问作者Alaa Khalila
相关产品推荐
相关产品推荐

