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

React.js+Node.js服务端响应时出现UnhandledPromiseRejection 304错误

问题原因分析
  • 核心触发点:HTTP 304状态码是缓存协商标识,代表请求的资源和浏览器本地缓存版本一致,服务端不会返回完整响应体。而Axios默认仅将200~299区间的状态码判定为请求成功,304会被判定为请求失败,抛出异常进入catch回调。
  • 代码层面的问题:
    1. 你在homepage路由中转发请求时,直接透传了前端带来的If-Modified-Since、If-None-Match等缓存协商头,触发了getPosts接口的304缓存判定。
    2. homepage路由中Axios请求的catch回调里注释了res.send逻辑,304触发错误后没有给前端返回响应,同时未被处理的Promise异常就抛出了UnhandledPromiseRejectionWarning警告。
    3. getPosts路由中混用了async/await和回调式的db.query,await对回调版本的数据库查询不生效,属于隐藏风险,虽不是304的直接诱因,但可能引发其他时序问题。
解决方案

分步骤调整即可修复:

  1. 处理缓存协商问题,避免304触发
    转发请求时删除缓存相关请求头,或给getPosts接口添加禁用缓存的响应头,示例如下:
// homepage路由中调整请求配置
const headers = { ...req.headers };
delete headers['if-modified-since'];
delete headers['if-none-match'];

或在getPosts接口返回时添加响应头:

res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
  1. 补全错误处理逻辑,避免未处理的Promise异常
    将homepage路由的请求逻辑调整为catch后置,所有异常都返回对应响应:
const headers = { ...req.headers };
delete headers['if-modified-since'];
delete headers['if-none-match'];
Axios.get('http://localhost:3001/getPosts', { headers })
  .then(response => res.send(response.data))
  .catch(err => {
    console.log('Error in homepage.js', err);
    if (err.response) {
      res.status(err.response.status).send(err.response.data);
    } else {
      res.status(500).send({ error: 'Internal server error' });
    }
  });
  1. 修正getPosts路由的async/await写法
    如果你的数据库实例支持Promise调用,调整为纯async/await写法避免时序问题:
router.get('/', authenticateToken, async (req, res) => {
  try {
    const result = await db.query('SELECT * FROM posts');
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    console.log(result);
    res.send(result);
  } catch (err) {
    console.log('HELLO FROM ERROR', err);
    res.send({ errorMessage: err });
  }
});
  1. 可选:配置Axios识别304为成功状态
    如果确实需要使用缓存逻辑,可以给Axios添加validateStatus配置,将304纳入成功状态范围:
// 前端请求或服务端代理请求的Axios配置中添加
validateStatus: (status) => (status >= 200 && status < 300) || status === 304

内容的提问来源于stack exchange,提问作者Kevin. J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:36:03