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

如何在module.exports长格式路由中为POST请求正确传递req、res参数

问题根因

你遇到的问题是Hapi框架和Express框架的路由处理函数签名不兼容,以及模块导出时的引用风险共同导致的:

  1. Hapi的路由处理函数原生签名为async (request, h) => {},而非你写的Express风格async (req, res) => {},框架只会给第一个参数注入完整的请求对象,第二个参数为Hapi内置的响应工具对象,你定义的第二个参数res不会被赋值,自然为空。
  2. 你在routes方法中通过module.exports引用处理函数,存在极低概率的导出时序问题,GET接口无参数所以未暴露问题,POST接口的参数打印放大了这个异常。

解决方案

第一步:修正处理函数签名

将new_endpoint的参数改为Hapi标准格式,用request接收请求对象,h作为响应工具:

new_endpoint: async (request, h) => {
  console.log(request) // 可正常拿到路径参数、请求头、请求体等所有请求信息
  return h.response(1).code(200) // 标准的Hapi响应写法,原直接return 1也可正常运行
}

第二步(可选,最优实践):优化导出逻辑避免引用风险

将处理函数提前定义在模块内部,直接在路由配置中引用函数变量,不需要从module.exports上取值,完全规避导出时序问题,同时完全符合你的原有代码结构和eslint规则:

// foo.js 完整修改示例
const existing_endpoint = async () => {
  /* 原有逻辑保持不变 */ 
}

const new_endpoint = async (request, h) => {
  console.log(request)
  return h.response(1).code(200)
}

module.exports = {
  routes: () => {
    return [
      {
        method: 'GET',
        path: '/existing_endpoint',
        handler: existing_endpoint
      }, 
      {
        method: 'POST',
        path: '/new_endpoint',
        handler: new_endpoint
      }
    ]
  }, 
  existing_endpoint,
  new_endpoint
}

注意事项

不要尝试在路由配置中直接调用处理函数(比如写handler: module.exports.new_endpoint(req, res)),路由配置需要传入的是函数引用,框架会在请求到达时自动调用该函数并注入参数,提前调用会必然出现变量未定义的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:45:01