Express.js中res.redirect()仅单路由生效问题求助
Express res.redirect() 在PATCH路由不生效的解决办法
问题核心:你用Axios发的是AJAX请求,和普通表单提交逻辑不一样——浏览器不会自动根据AJAX请求的重定向响应来跳转页面。哪怕服务器返回了303重定向,Axios只会默默获取重定向后的页面内容,但不会刷新浏览器页面或修改地址栏。
解决办法一:前端手动跳转
这是最直接的方案,在Axios请求成功后,用window.location.href强制触发页面跳转:
async function patchReq(commentLink, val) { try { await axios.patch(commentLink, { "newComment": val }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); // 请求成功后手动跳转到/about页面 window.location.href = '/about'; } catch (e) { console.log(e); } }
解决办法二:服务器返回跳转指令,前端配合
如果想让服务器控制跳转逻辑,可以让PATCH路由返回JSON格式的跳转指令,前端拿到后执行跳转:
服务端代码修改
app.patch("/about/:id", (req, res) => { console.log(req.body); const { id } = req.params, newComment = req.body.newComment, oldComment = commentDB.find(c => c.id === id); oldComment.comment = newComment; // 返回JSON告知前端需要跳转的地址 res.json({ redirect: '/about' }); });
前端代码修改
async function patchReq(commentLink, val) { try { const response = await axios.patch(commentLink, { "newComment": val }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); // 检查返回结果中的redirect字段,执行跳转 if (response.data.redirect) { window.location.href = response.data.redirect; } } catch (e) { console.log(e); } }
补充:为什么POST路由的redirect能生效?
因为POST路由对应的应该是普通表单提交(而非AJAX请求),浏览器处理表单提交的响应时,会自动遵循3xx重定向规则跳转到目标页面,这和AJAX的请求处理逻辑完全不同。
内容的提问来源于stack exchange,提问作者user21232835
相关产品推荐
相关产品推荐

