How do I get the POST data from a nuxtjs server middleware? So far I've managed to do it for GET, but for POST the body is just not there. req.body is undefined.
Add this to nuxt.config.js:
serverMiddleware: [
'~/api/v1/index.js'
],
and then create a file /api/v1/index.js with:
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)
})
Key line is app.use(bodyParser.json())
Even if you are not using express, the code is still very similar.
You do not need to use express because nuxt server already running connect instance for this. Just do this for receiving the POST request:
yourservermiddleware.js -
export default {
path: '/yourservermiddlware',
async handler(req, res, next) {
req.on('data', async (data) => {
let payload = JSON.parse(data.toString())
console.log("received request", payload)
res.end(JSON.stringify('send back what you want'))
next()
})
}
}
P.S. and do not forget to register servermiddleware at the nuxt.config.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With