POST请求中Express render()方法无法生效的问题求助
POST请求无法实现页面跳转的解决办法
问题出在fetch是异步AJAX请求,它只会接收后端返回的响应内容,不会自动触发浏览器的页面跳转。后端用res.render返回的渲染页面,只是作为数据传给了fetch,并没有被浏览器加载显示。
下面是两种可行的解决方式:
方式一:通过重定向实现跳转
修改后端代码
先新增GET路由用于渲染目标页面,再在POST路由里返回重定向并传递数据:
app.set('view engine','ejs'); app.use("/",express.static('public')); // 新增GET路由,用于渲染目标页面 app.get("/movie-selected", (req,res)=>{ // 从URL参数中获取数据 const movieData = { movieName: req.query.movieName, image: req.query.image, city: req.query.city, country: req.query.country }; res.render("../view/movie-selected", movieData); }) app.post("/sendMovieData", async(req,res)=>{ console.log(req.body); // 对参数做URL编码,避免特殊字符导致的问题 const redirectUrl = `/movie-selected?movieName=${encodeURIComponent(req.body.movieName)}&image=${encodeURIComponent(req.body.image)}&city=${encodeURIComponent(req.body.city)}&country=${encodeURIComponent(req.body.country)}`; res.redirect(redirectUrl); })
修改前端fetch代码
在fetch的响应处理中,检测到重定向后跳转到目标URL:
let requestBody = { "movieName": movie.getAttribute("data-movieName"), "image": e.target.src, "city": JSON.parse(localStorage.getItem("city_country")).city, "country": JSON.parse(localStorage.getItem("city_country")).country } fetch('/sendMovieData', { method: "POST", headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(requestBody) }) .then(response => { // 检测到重定向时跳转 if (response.redirected) { window.location.href = response.url; } });
方式二:改用表单提交(更简单)
如果不需要保留AJAX的异步特性,直接用HTML表单提交,浏览器会自动处理页面跳转:
前端代码(替换原fetch部分)
<!-- 用隐藏表单传递数据 --> <form id="movieForm" action="/sendMovieData" method="POST"> <input type="hidden" name="movieName" id="movieName"> <input type="hidden" name="image" id="image"> <input type="hidden" name="city" id="city"> <input type="hidden" name="country" id="country"> </form> <script> // 点击事件中填充表单并提交 const movie = /* 你的movie元素 */; const cityCountry = JSON.parse(localStorage.getItem("city_country")); document.getElementById("movieName").value = movie.getAttribute("data-movieName"); document.getElementById("image").value = e.target.src; document.getElementById("city").value = cityCountry.city; document.getElementById("country").value = cityCountry.country; document.getElementById("movieForm").submit(); </script>
后端代码(小幅度调整)
app.set('view engine','ejs'); app.use("/",express.static('public')); // 配置解析表单数据的中间件 app.use(express.urlencoded({ extended: true })); app.post("/sendMovieData", async(req,res)=>{ console.log(req.body); // 直接把表单数据传给模板渲染 res.render("../view/movie-selected", req.body); })
内容的提问来源于stack exchange,提问作者Cristian Babalau
相关产品推荐
相关产品推荐

