部署于Render的MERN应用Axios POST请求失效,求正确请求地址
部署到Render后Axios POST请求失败的解决方案
问题描述
我开发的简易MERN应用,本地运行时点击提交按钮能通过Axios.post把anime对象存入MongoDB并渲染到页面,但部署前端和后端到render.com后,POST请求无法添加对象。
相关代码
前端App组件代码:
const [animeList, setAnimeList] = useState([]); useEffect(() => { Axios.get("https://recom-59hb.onrender.com/read").then((response) => { setAnimeList(response.data); }); }, []); const addAnime = async (anime) => { await Axios.post("http://localhost:10000/insert", anime); console.log(anime); };
后端index.js代码:
app.post("/insert", async (req, res) => { const title = req.body.title; const opinion = req.body.opinion; const image = req.body.image; const anime = new AnimeModel({ title: title, opinion: opinion, image: image, }); try { await anime.save(); res.send("inserted data"); } catch (err) { console.log(err); } });
我试过把POST链接改成"insert"和"website-name.onrender.com/insert"都没用,请问正确的请求地址应该是什么?
解决方案
正确的POST请求地址:必须使用后端部署的完整HTTPS地址拼接接口路径,也就是和你GET请求用的域名完全一致:
https://recom-59hb.onrender.com/insert- 不能用
http://localhost:10000/insert:这是本地开发的地址,部署到Render后该地址无效 - 不能只写
"insert":这是相对路径,若前端是单独部署的静态站点,相对路径会指向前端域名而非后端API域名,导致请求错误 - 必须使用HTTPS:Render部署的服务默认启用HTTPS,HTTP请求会被浏览器拦截,无法正常发送
- 不能用
额外必要检查项:
- 配置CORS跨域:后端必须允许前端部署地址的跨域请求,可通过
cors包实现:const cors = require('cors'); // 替换为你的前端Render部署地址,生产环境不建议用*允许所有域名 app.use(cors({ origin: "https://你的前端部署地址.onrender.com" })); - 使用环境变量管理API地址:避免硬编码地址,提升部署灵活性。在前端项目根目录创建
.env文件:
代码中调用方式:REACT_APP_API_URL=https://recom-59hb.onrender.comawait Axios.post(`${process.env.REACT_APP_API_URL}/insert`, anime);
- 配置CORS跨域:后端必须允许前端部署地址的跨域请求,可通过
内容的提问来源于stack exchange,提问作者Zer0pearl
相关产品推荐
相关产品推荐

