programing

Nuxtjs에서 POST 요청 파라미터를 읽는 방법

randomtip 2022. 8. 17. 20:57
반응형

Nuxtjs에서 POST 요청 파라미터를 읽는 방법

nuxtjs asyncData 함수로 POST 요청 파라미터를 읽는 간단한 방법이 있습니까?

다음은 예를 제시하겠습니다.

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 페이지로 전송합니다.

클릭아웃.표시하다

async asyncData(context) {
    // some way how to get the value of POST param "id"
    return { id }
}

마침내 나는 그것을 해결하는 방법을 찾았다.이 방법이 최선인지 잘 모르겠습니다만, 어쨌든 효과가 있습니다.

서버 미들웨어 서버 미들웨어/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.config.syslog

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

클릭아웃.표시하다

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

디폴트 동작은 사용하지 않는 것이 좋습니다.form다음과 같이 송신 핸들러를 정의합니다.

<template>
<form @submit.prevent="submit">
     <input type="hidden" name="id" v-model="item.id" />
     <input type="submit" value="submit" />
</form>
</template>

그리고 다음과 같이 메서드를 제출합니다.

  methods:{
     submit(){
       this.$router.push({ name: 'clickout', params: { id: this.item.id } })
     
        }
     }

대상 컴포넌트에서 다음을 수행합니다.

     asyncData(context) {

         return  this.$route.params.id;
    }

서버 측에서 asyncData가 호출되면 사용자 요청의 req 및 res 개체에 액세스할 수 있습니다.

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

참조: https://nuxtjs.org/guide/async-data/ #use-code-req-code-res-code-displaced

조금 늦은 감이 있지만 이게 도움이 될 것 같아요.

.vue 파일에서 nuxt 라우터 루트 개체를 가져옵니다.

this.$route

경로, 해시, 매개 변수 및 쿼리와 같은 유용한 정보를 저장합니다.

상세한 것에 대하여는, 이것을 봐 주세요.

언급URL : https://stackoverflow.com/questions/54289615/how-to-read-post-request-parameters-in-nuxtjs

반응형