How to read POST request parameters in nuxtjs?

旧时模样 提交于 2019-12-21 06:25:03

问题


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

回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/54289615/how-to-read-post-request-parameters-in-nuxtjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!