React中用Axios发Post请求报404,Express服务Postman可正常访问
React跨域POST请求404问题解决
问题描述
React应用运行在3000端口,Express服务运行在9000端口,使用axios发起POST请求时浏览器控制台提示Failed to load resource: the server responded with a status of 404 (Not Found),但Postman中请求该接口可正常返回结果。
React代码
axios.post("/").then((response)=>{ console.log(response.data) }).catch((e)=>{ console.log(e.response.data) this.out = e.response.data })
Express代码
app.post("/", (req, res) => { console.clear() console.log(req.body) res.end("req") })
问题原因
直接用axios.post("/")发起请求时,请求会默认指向React应用所在的3000端口,而非Express服务的9000端口,3000端口下不存在对应的POST接口,因此返回404。而Postman是直接请求9000端口的接口,所以能正常响应。
解决方案
方案1:指定完整服务地址
修改axios请求,直接指向Express服务的9000端口:
axios.post("http://localhost:9000/").then((response)=>{ console.log(response.data) }).catch((e)=>{ console.log(e.response?.data) this.out = e.response?.data })
方案2:配置React代理(推荐)
在React项目的package.json文件中添加代理配置,将请求转发到9000端口:
{ // 其他配置... "proxy": "http://localhost:9000" }
配置完成后,无需修改原axios请求代码,React会自动将请求代理到Express服务。
方案3:添加跨域中间件
为避免后续出现跨域报错,在Express服务中配置cors中间件:
- 安装依赖:
npm install cors
- 在Express代码中引入并使用:
const cors = require('cors'); app.use(cors()); app.post("/", (req, res) => { console.clear() console.log(req.body) res.end("req") })
内容的提问来源于stack exchange,提问作者Divyansh undley
相关产品推荐
相关产品推荐

