Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the POST data from a nuxtjs server middleware?

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.

like image 301
ioan Avatar asked Nov 04 '25 16:11

ioan


2 Answers

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.

like image 93
ioan Avatar answered Nov 06 '25 09:11

ioan


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

like image 21
Michael Perelman Avatar answered Nov 06 '25 11:11

Michael Perelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!