Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read POST request parameters in Nuxtjs?

is there some simple way how to read POST request parameters in nuxtjs asyncData function?

Here's an example:

Form.vue:

<template>
    <form method="post" action="/clickout" target="_blank">
         <input type="hidden" name="id" v-model="item.id" />
         <input type="submit" value="submit" />
    </form>
</template>

submitting previous form routes to following nuxt page:

Clickout.vue

async asyncData(context) {
    // some way how to get the value of POST param "id"
    return { id }
}
like image 736
Martin Rázus Avatar asked Jan 21 '19 12:01

Martin Rázus


3 Answers

Finally I found following way how to solve that. I'm not sure if it's the best way, anyway it works :)

I needed to add server middleware server-middleware/postRequestHandler.js

const querystring = require('querystring');

module.exports = function (req, res, next) {
    let body = '';

    req.on('data', (data) => {
        body += data;
    });

    req.on('end', () => {
        req.body = querystring.parse(body) || {};
        next();
    });
};

nuxt.config.js

serverMiddleware: [
        { path: '/clickout', handler: '~/server-middleware/postRequestHandler.js' },
    ],

Clickout.vue

async asyncData(context) {
    const id = context.req.body.id;
    return { id }
}
like image 120
Martin Rázus Avatar answered Nov 07 '22 07:11

Martin Rázus


When asyncData is called on server side, you have access to the req and res objects of the user request.

export default {
  async asyncData ({ req, res }) {
    // Please check if you are on the server side before
    // using req and res
    if (process.server) {
      return { host: req.headers.host }
    }

    return {}
  }
}

ref. https://nuxtjs.org/guide/async-data/#use-code-req-code-code-res-code-objects

like image 21
Kumar Aman Avatar answered Nov 07 '22 06:11

Kumar Aman


I recommend to not use the default behavior of form element, try to define a submit handler as follows :

<template>
<form @submit.prevent="submit">
     <input type="hidden" name="id" v-model="item.id" />
     <input type="submit" value="submit" />
</form>
</template>

and submit method as follows :

  methods:{
     submit(){
       this.$router.push({ name: 'clickout', params: { id: this.item.id } })
     
        }
     }

in the target component do:

     asyncData(context) {

         return  this.$route.params.id;
    }
like image 2
Boussadjra Brahim Avatar answered Nov 07 '22 07:11

Boussadjra Brahim