React调用Node API路径异常:/profile被追加至请求路径
问题解决:React路由页面中API请求路径错误的修复
问题原因
在个人资料页(http://localhost:3000/profile)使用相对路径发起axios请求时,浏览器会自动拼接当前页面的路径(/profile)到请求URL前,再结合package.json里的代理配置,最终生成错误的请求地址:http://localhost:5000/api/profile/posts/profile/username。而首页处于根路径(/),相对路径不会额外拼接,所以请求正常。
修复方案
1. 添加根路径前缀(推荐)
在请求URL前加上/,将其改为绝对路径,避免基于当前页面路径拼接:
const Feed = ({ username }) => { const [posts, setPosts] = useState([]); useEffect(() => { const fetchPosts = async () => { const res = username ? await axios.get("/posts/profile/" + username) : await axios.get("/posts/timeline/63cf5546b59c8100a042538d"); setPosts(res.data); }; fetchPosts(); }, [username]); }
添加/后,请求会基于代理的根路径(http://localhost:5000/api)发起,最终生成正确的URL:http://localhost:5000/api/posts/profile/username。
2. 配置axios全局基础URL
在项目入口文件(如index.js)或单独的axios配置文件中,设置全局baseURL:
import axios from 'axios'; axios.defaults.baseURL = '/api';
之后发起请求时直接使用相对路径即可,无需担心页面路径影响:
const res = username ? await axios.get("posts/profile/" + username) : await axios.get("posts/timeline/63cf5546b59c8100a042538d");
3. 使用完整API地址(不推荐)
直接在请求中写入完整API地址,跳过代理:
const res = username ? await axios.get("http://localhost:5000/api/posts/profile/" + username) : await axios.get("http://localhost:5000/api/posts/timeline/63cf5546b59c8100a042538d");
此方法仅适合开发阶段,生产环境需替换为正式域名,灵活性较差。
内容的提问来源于stack exchange,提问作者Shiv Shankar Prasad
相关产品推荐
相关产品推荐

