简体   繁体   中英

How to pass the data to vue from node.js, in nuxt.js ssr?

I want to pass the firestore data to vue files from Node.js (Express). Because I must use firestore's getCollections() method. It cannot run in client side.

I build nuxt-ssr to deploy google-cloud-functions and cloud-hosting. I refer to this article.( https://itnext.io/how-to-create-a-ssr-serverless-app-with-firebase-nuxt-js-in-an-hour-6e6e03d0b3b8 ) This directory structure is like below.

---public (deploy to cloud-hosting)
|
|-src ( nuxt build to functions directory)
|
|-functions (have Node.js and deploy to cloud-functions)
|
|-firebase.json
:

I guess my purpose can achieved by index.js in functions dir. It looks like below.

const functions = require('firebase-functions')
const express = require('express')
const { Nuxt } = require('nuxt')

const app = express()

const config = {
  dev: false,
  buildDir: 'nuxt',
  build: {
    publicPath: '/'
  }
}
const nuxt = new Nuxt(config)

function handleRequest(req, res) {
  res.set('Cache-Control', 'public, max-age=600, s-maxage=1200')
  nuxt.renderRoute('/').then(result => {
    res.send(result.html)
  }).catch(e => {
    res.send(e)
  })
}

app.get('*', handleRequest)
exports.nuxtApp = functions.https.onRequest(app)

How I should change this code? Please give me your wisdom.

I had answer.

nuxt.renderRoute() can pass the data in argument as optional. ( https://nuxtjs.org/api/nuxt-render-route )

So in functions dir, I should change the code like below.

  :
function handleRequest(req, res) {
  res.set('Cache-Control', 'public, max-age=600, s-maxage=1200')
  **req.data = "some data from firestore"**
  nuxt.renderRoute('/', **{ req }** ).then(result => {
    res.send(result.html)
  }).catch(e => {
    res.send(e)
  })
}
  :

And in src dir, vue.js file looks like below.

<template>
    <p>{{ apiResult }}</p>
</template>

<script>
export default {
  asyncData(context) {
    return { apiResult: context.req.data };
  }
}
</script>

<template>
</template>

It will view the req.data like some data from firestore .
I could achieve my purpose. Thank you guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM