将Nuxt.js SSR应用程序部署到生产中会出错

时间:2019-02-12 22:56:14

标签: javascript node.js vue.js nuxt.js

我已经用Nuxt.js构建了通用应用程序,现在我想部署它,但是我发现该过程非常混乱。

这是我package.json中的脚本部分

"scripts": {
    "dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
    "build": "nuxt build",
    "start": "cross-env NODE_ENV=production node server/index.js",
    "generate": "nuxt generate"
}

到目前为止,我一直在使用npm run dev没问题。当我运行npm run build时,一切似乎都运行良好,然后当我运行npm run start时,该应用程序也成功运行,但似乎未执行我最近的 build 代码,相反,它似乎正在运行执行npm run dev时运行的相同开发代码。

我还尝试执行nuxt start,这在执行npm run build之后可以运行,但是如果我这样做,应用程序就会崩溃。

构建后如何在生产中运行我的SSR应用程序? npm run build是否应该构建任何Node.js后端内容?

这是我的server / index.js

// Debug in development
process.env.DEBUG = 'nuxt:*'

require('dotenv').config()
const env = require('../config')
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const redis = require('./api/adapters/Redis')
const host = env.public.host
const port = env.public.port

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  next();
});

app.set('port', port)

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(env.public.environment === '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()
  }

  // Connect to redis
  redis.connect()  // <-- This creates a connection with redis server, and doesn't seem to connect when running `nuxt start`, hence the error.
  require('fs').writeFile('ZZZ.txt', 'YES', 'utf8', () => {}) // <-- as an experiment ZZZ.txt file gets written when `npm run dev` but not when `nuxt start` is ran.

  // Handle errors
  process.once('uncaughtException', err => {
    redis.disconnect()
    process.exit(1)
  });

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

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()

0 个答案:

没有答案