前端调用/auth/signin接口遇404错误,代理配置后仍异常求助
解决前端代理后登录接口404问题
问题分析
你的代理配置将前端请求转发到http://localhost:8800/api,当调用axios.post("/auth/signin")时,实际转发地址为http://localhost:8800/api/auth/signin。但后端登录接口实际路径是http://localhost:8800/auth/signin(Insomnia直接调用正常),路径不匹配导致404错误。
解决方案
方案1:统一后端接口前缀(推荐)
给后端登录接口添加/api前缀,使其路径变为/api/auth/signin。这样前端请求/auth/signin会被代理正确转发到http://localhost:8800/api/auth/signin,既匹配后端接口,也保持和视频接口的前缀一致性。
方案2:调整前端请求路径(仅开发环境临时使用)
直接在请求中指定后端完整地址,绕过代理:
const handleLogin = async (e)=> { e.preventDefault(); try{ const res = await axios.post("http://localhost:8800/auth/signin", {username, password}); console.log(res.data); }catch(err){ console.log(err); } }
注意:此方法仅适用于开发环境,生产环境部署会触发跨域问题,不建议长期使用。
方案3:修改前端代理配置
- 更新
package.json中的proxy字段,移除末尾的/api:
"proxy": "http://localhost:8800"
- 调整所有前端接口请求路径,添加
/api前缀:- 视频接口请求改为
axios.get("/api/videos") - 登录接口请求改为
axios.post("/api/auth/signin", {username, password})
- 视频接口请求改为
修改代理配置后,必须重启前端开发服务(停止npm start后重新启动)才能生效。
内容的提问来源于stack exchange,提问作者Zachary Song
相关产品推荐
相关产品推荐

