You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express中POST请求调用res.render后客户端无跳转如何解决?

根本原因

XMLHttpRequest发起的是异步AJAX请求,浏览器只会将服务端返回的内容交给JS逻辑处理,不会主动渲染返回的HTML页面或触发跳转。当前你服务端返回的search页面内容已经被XMLHttpRequest对象接收,但缺少后续处理逻辑,因此客户端没有反应。

解决方案

方案1:使用原生表单提交(推荐,无需额外JS逻辑)

如果需求是提交参数后跳转展示搜索结果页,直接使用HTML表单提交即可,不需要写AJAX代码:

<form method="POST" action="/search">
  <input type="text" name="key" id="search">
  <button type="submit">搜索</button>
</form>

表单提交后浏览器会自动渲染服务端返回的search页面,完全符合预期效果。
注意:需要在Express中添加表单解析中间件才能拿到参数:

app.use(express.urlencoded({ extended: true }))

方案2:保留AJAX逻辑,前端手动处理响应

如果必须使用AJAX发起请求,可以选择以下两种处理方式:

方式A:前端主动跳转

前端添加响应监听逻辑,拿到服务端返回的跳转地址后触发页面跳转:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', '/search', true);
// 添加请求头,让服务端可以正确解析JSON格式参数
xmlHttp.setRequestHeader('Content-Type', 'application/json');
xmlHttp.onload = function() {
  const resp = JSON.parse(xmlHttp.responseText);
  // 主动跳转至目标页面
  location.href = resp.targetUrl;
}
var searchData = {
    key: search.value,
}
xmlHttp.send(JSON.stringify(searchData));

服务端对应修改为返回跳转地址:

// 提前添加JSON解析中间件
app.use(express.json())

app.post('/search', (req, res) =>{
    console.log('render search')
    // 返回跳转地址,可携带搜索参数
    res.json({targetUrl: `/search_page?key=${req.body.key}`})
})
// 新增GET接口返回搜索页面
app.get('/search_page', (req, res) => {
    res.render('search', {key: req.query.key})
})

方式B:直接替换当前页面内容

如果不需要修改地址栏,只需要展示返回的搜索页面,可以直接将响应内容写入当前文档:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', '/search', true);
xmlHttp.setRequestHeader('Content-Type', 'application/json');
xmlHttp.onload = function() {
  document.open();
  document.write(xmlHttp.responseText);
  document.close();
}
var searchData = {
    key: search.value,
}
xmlHttp.send(JSON.stringify(searchData));

内容的提问来源于stack exchange,提问作者user15455820

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:06:01