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

Node.js表单提交抛出InternalServerError: stream not readable问题排查

问题描述

我正在开发一个包含注册、登录表单提交功能的Node.js项目,服务器运行正常且已成功连接MongoDB,其余功能均无异常,但提交表单输入时抛出错误:InternalServerError: stream not readable。

相关代码片段

// For Passing Application JSON
app.use(express.urlencoded({extended:true}));
app.use(express.json());

// Set Cookie Parser, Session and Flash
app.use(cookieParser(process.env.COOKIES_PARSER_SECERET));
app.use(session({
  secret : process.env.COOKIES_SECRET,
  cookie: {maxAge:60000},
  resave: true,
  saveUninitialized: true
}));

错误日志

Server started on port 5000
MongoDB Connected....
InternalServerError: stream is not readable
    at readStream (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\raw-body\index.js:178:17)
    at getRawBody (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\raw-body\index.js:109:12)
    at read (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\body-parser\lib\read.js:79:3)
    at urlencodedParser (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\body-parser\lib\types\urlencoded.js:116:5)
    at Layer.handle [as handle_request] (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\express\lib\router\layer.js:95:5)      
    at trim_prefix (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\express\lib\router\index.js:328:13)
    at C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\express\lib\router\index.js:286:9
    at Function.process_params (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\express\lib\router\index.js:280:10)
    at serveStatic (C:\Users\ED JOSE\Documents\Loctech - Car Booking Web Application\node_modules\serve-static\index.js:75:16)

可能的原因与修复方案

  • 中间件顺序错误:从错误栈可见,serve-static静态资源中间件在urlencodedParser表单解析中间件之前执行。静态资源中间件会提前消耗请求流,导致后续body-parser无法读取。修复时需调整顺序,把express.urlencoded、express.json这类请求体解析中间件放在serve-static之前。
  • 请求流被提前消耗:排查body-parser之前的所有中间件和代码,确认是否存在手动读取请求流的操作(比如req.pipe()、req.read())。请求流一旦被读取,body-parser就无法再获取可读流,需删除这类提前消费流的逻辑。
  • 表单提交类型不匹配:检查前端表单的enctype属性:普通表单提交用application/x-www-form-urlencoded;带文件上传的表单需用multipart/form-data,此时express.urlencoded无法处理,要改用multer中间件。错误的enctype会引发流解析异常。
  • 依赖版本兼容问题:部分旧版express和body-parser组合存在流处理bug,尝试更新到稳定版本:
    npm update express body-parser
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:25:27