ExpressJS with NuxtJS middleware passing post data to page

Viewed 2974

Can someone help me understand how to pass data from post request to the nuxt page that is loaded. I dont know how to send the data to the page that will be loaded.

I want to be able to process the POST request, then send that data for usage on the following page. I am open to suggestions but I can't find proper documentation, tutorials or examples to accomplish this task.

I don't want to use axios here (with JSON type response), because I would prefer to send POST data and load new page. Therefor if page is reloaded, POST data must be submitted again.

const express = require('express')
const bodyParser = require('body-parser')

const { Nuxt, Builder } = require('nuxt')
const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.set('port', port)

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // Routes added
  app.post('/events/booking', function (req, res, next) {
    console.log('REQUEST:', req.body)
    res.set('eventId', req.body.eventId)
    res.set('moreData', ['some', 'more', 'data'])
    next()
  })

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  app.listen(port, host)
  console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console
}
start()
1 Answers

I believe the source of your issue is the disconnect between Nuxt's implementation of Express, the deprecation/version-conflicts of bodyParser middleware and/or the Node event system.

I would personally take a step back by removing the custom express routing, handle the body parsing yourself in the middleware and take advantage of the Vuex store.


store/index.js

export const state = () => ({
  postBody: null,
  postError: null
})

export const mutations = {
  postBody: (state, postBody) => {
    state.postBody = postBody;
  },
  postError: (state, postError) => {
    state.postError = postError;
  },
}

export const getters = {
  postBody: state => state.postBody,
  postError: state => state.postError,
}

middleware/index.js

export default ({req, store}) => {
  if (process.server && req && req.method === 'POST') {
    return new Promise((resolve, reject) => {
      req.on('data', data => resolve(store.commit('postBody', JSON.parse(data))));
      req.on('error', data => reject(store.commit('postError', JSON.parse(data))));
    })
  }
}

pages/index.vue

<template>
  <div>
    <h1>Test page</h1>
    <div v-if="postBody">
      <h2>post body</h2>
      <p>{{postBody}}</p>
    </div>
    <div v-if="postError">
      <h2>post error</h2>
      <p>{{postError}}</p>
    </div>
    <div v-if="!postError && !postBody">
      Please post JSON data to this URL to see a response
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    middleware: 'post-data', 
    computed: mapGetters({
      postBody: 'postBody',
      postError: 'postError'
    })
  }
</script>

Below is a live and working example project of the above. POST JSON data using a client app (Postman, web form, etc) to see the posted data rendered on the page.

Live Code: https://glitch.com/edit/#!/terrific-velociraptor

Live Example: https://terrific-velociraptor.glitch.me/

Related