【问题标题】:ExpressJS with NuxtJS middleware passing post data to page带有 NuxtJS 中间件的 ExpressJS 将发布数据传递到页面
【发布时间】:2019-02-18 23:18:39
【问题描述】:

谁能帮助我了解如何将数据从发布请求传递到加载的 nuxt 页面。我不知道如何将数据发送到将要加载的页面。

我希望能够处理 POST 请求,然后在下一页发送该数据以供使用。我愿意接受建议,但我找不到合适的文档、教程或示例来完成这项任务。

我不想在这里使用 axios(带有 JSON 类型的响应),因为我更愿意发送 POST 数据并加载新页面。因此,如果页面被重新加载,必须重新提交 POST 数据。

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

【问题讨论】:

    标签: express vue.js nuxt.js


    【解决方案1】:

    我认为您的问题的根源在于 Nuxt 的 Express 实现、bodyParser 中间件的弃用/版本冲突和/或 Node 事件系统之间的脱节。

    我个人会后退一步,删除自定义快速路由,在中间件中自己处理正文解析,并利用 Vuex 存储。


    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>
    

    下面是上面的一个实际工作的示例项目。使用客户端应用(Postman、Web 表单等)发布 JSON 数据以查看在页面上呈现的发布数据。

    直播代码:https://glitch.com/edit/#!/terrific-velociraptor

    实时示例:https://terrific-velociraptor.glitch.me/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 2022-12-14
      • 2020-10-15
      • 2020-07-16
      • 2020-09-16
      • 1970-01-01
      相关资源
      最近更新 更多