How to read POST request parameters in nuxtjs?

2020-06-21 06:34发布

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

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

3条回答
Juvenile、少年°
2楼-- · 2020-06-21 06:37

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 }
}
查看更多
Animai°情兽
3楼-- · 2020-06-21 06:37

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

<template>
<form @submit="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:

   async asyncData(context) {

         return  this.$route.params.id;
    }
查看更多
Animai°情兽
4楼-- · 2020-06-21 06:53

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

查看更多
登录 后发表回答