如何在Nuxtjs中读取POST请求参数? [英] How to read POST request parameters in Nuxtjs?

查看:423
本文介绍了如何在Nuxtjs中读取POST请求参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些简单的方法来读取nuxtjs asyncData函数中的POST请求参数?

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

这是一个例子:

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>

将先前的表单路由提交到以下nuxt页面:

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 :)

我需要添加服务器中间件 server-middleware/postRequestHandler.js

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

nuxt.config.js

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

Clickout.vue

Clickout.vue

async asyncData(context) {
    const id = context.req.body.id;
    return { id }
}

这篇关于如何在Nuxtjs中读取POST请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆