如何从 nuxtjs 服务器中间件获取 POST 数据?

ioa*_*nb7 4 express nuxt.js

如何从 nuxtjs 服务器中间件获取 POST 数据?到目前为止,我已经成功地为 GET 做到了这一点,但对于 POST 来说,正文不存在。req.body未定义。

ioa*_*nb7 6

将其添加到nuxt.config.js

serverMiddleware: [
  '~/api/v1/index.js'
],
Run Code Online (Sandbox Code Playgroud)

然后创建一个文件/api/v1/index.js

const bodyParser = require('body-parser')
const app = require('express')()
module.exports = { path: '/api', handler: app }
app.use(bodyParser.json());
app.post('/newsletter/subscribe', (req, res) => {
  res.json(req.body)
})
Run Code Online (Sandbox Code Playgroud)

关键是app.use(bodyParser.json()) 即使您不使用express,代码仍然非常相似。