简体   繁体   中英

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

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

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

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

Maybe it is a little bit late but I think this might help.

In your .vue file get the nuxt router route object:

this.$route

It stores some useful information like the path, hash, params and the query.

Take a look at this for more details on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM