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

Axios GET请求未指向正确URL,配置代理后仅profile请求失效如何解决

问题原因

该问题是相对路径请求拼接当前页面URL导致的:

  • 你调用axios.get("posts/profile/"+username)时使用的是不带开头斜杠的相对路径,浏览器会自动将当前页面的路径作为基路径进行拼接。
  • 该请求触发时你正处于/profile/:username的React路由页面下(比如访问http://localhost:3000/profile/matt),浏览器会把相对路径posts/profile/matt拼接到当前页面路径后,得到/profile/posts/profile/matt的请求路径,经过代理转发后就变成了你日志中看到的错误路径/api/profile/posts/profile/matt。
  • 另一个timeline请求正常是因为它是在首页(路径为/)触发的,相对路径拼接后得到/posts/timeline/xxx,符合预期。
解决方案

两种方案任选其一即可:

  1. 给请求路径添加开头斜杠,改为根路径绝对路径:
const res = username 
            ? await axios.get("/posts/profile/"+username)
            : await axios.get("/posts/timeline/6120b0e07ea0361eb4982b1c");

开头加/代表路径从站点根目录开始计算,不会受当前页面路由影响,请求路径会直接变为/posts/profile/matt,代理转发后会得到预期的/api/posts/profile/matt。

  1. 统一配置axios全局baseURL,避免相对路径问题:
    在项目入口文件(比如index.js)中添加全局配置:
import axios from 'axios';
axios.defaults.baseURL = '/api';

配置后所有请求都会自动加上/api前缀,你后续写请求时可以直接写接口后缀即可,示例:

// 不需要手动加前缀,最终请求路径为 /api/posts/profile/matt
const res = username 
            ? await axios.get("posts/profile/"+username)
            : await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:36:03