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 }
}
                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 }
}
                        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
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;
    }
                        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