Node.js接收POST请求后未执行重定向问题求助
问题分析与解决方案
你遇到的问题核心是:fetch作为AJAX异步请求,默认不会自动触发浏览器的页面跳转——服务器返回的重定向响应只会被fetch接收,但不会让浏览器跳转到/register页面,这就是你看不到跳转、也无报错的原因。
以下是两种可行的解决思路:
解决方法1:服务器返回跳转指令,前端主动处理
把服务器的重定向逻辑改为返回JSON格式的跳转地址,前端拿到响应后手动触发页面跳转。
修改服务器端代码
router.post("/barcode", (req, res) => { try { console.log(req.body); // 替换重定向,返回跳转指令 return res.json({ redirectUrl: "/register" }); } catch (error) { console.error("Error:", error); res.status(500).send("Internal Server Error"); } });
修改前端代码
async function sendrollno(rollno) { console.log("send roll no called"); const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ rollno: rollno }), }; try { const response = await fetch("http://localhost:3000/barcode", options); const data = await response.json(); console.log('POST request successful'); // 拿到跳转地址后,触发页面跳转 if (data.redirectUrl) { window.location.href = data.redirectUrl; } } catch (error) { console.error('Error during POST request:', error); throw error; } }
解决方法2:改用表单提交(自动跟随重定向)
浏览器原生的表单提交会自动跟随服务器的重定向响应,如果你想保留服务器端的重定向逻辑,可以放弃fetch,改用表单提交。
前端代码示例
function sendrollno(rollno) { console.log("send roll no called"); // 动态创建表单 const form = document.createElement('form'); form.method = 'POST'; form.action = 'http://localhost:3000/barcode'; // 添加隐藏字段传递rollno const input = document.createElement('input'); input.type = 'hidden'; input.name = 'rollno'; input.value = rollno; form.appendChild(input); // 提交表单 document.body.appendChild(form); form.submit(); document.body.removeChild(form); }
注:如果服务器要求请求体为JSON格式,需要调整表单的提交方式,或者直接在页面中编写静态表单并通过按钮触发提交。
补充:坚持用fetch处理重定向
fetch默认会自动跟随重定向(默认配置redirect: 'follow'),但只会获取重定向后的响应内容,不会改变页面。你可以手动检查响应的redirected属性,再触发跳转:
async function sendrollno(rollno) { // 其他代码不变 try { const response = await fetch("http://localhost:3000/barcode", options); // 检查是否被重定向 if (response.redirected) { window.location.href = response.url; } console.log('POST request successful'); } catch (error) { console.error('Error during POST request:', error); throw error; } }
内容的提问来源于stack exchange,提问作者Amit Kumar
相关产品推荐
相关产品推荐

