首页 > 解决方案 > 节点/快递: res.body 未定义

问题描述

(我已经阅读了其他类似 OP 的答案,但它们并没有解决我的问题。我已经在使用express.json()

在下面的代码中,res.bodyundefined.

app.use(cors({
   origin: '*',
   credentials: true,
   optionSuccessStatus: 200
}))

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:4200')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
  res.header('Access-Control-Allow-Methods', 'POST, GET')
  next()
})

app.use(cookieParser())

app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ extended: true, limit: '50mb' }))

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

app.post('/new-data', ensureLoggedIn('/auth/facebook'), (req, res) => {
  console.log(res.body) // logs undefined
})

我发送到服务器的是:

fetch('/new-data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ data })
})

其中data是一个包含 8 个图像的数组作为 Base64 字符串,每个大约 1.5Mb,我可以在我的 Chrome 网络面板上看到 POST 请求正确发出。

标签: node.jsjsonexpressbody-parser

解决方案


因为你得到 res.body ,你应该得到 req.body 。


推荐阅读