NuxtJs serverMiddleware导致生产错误

时间:2018-11-21 07:55:49

标签: express vue.js nuxt.js

NuxtJs应用在npm run dev上运行良好,但npm run build导致以下错误

enter image description here

这是我的server/index.js

require('dotenv').config()

const express = require('express')
const { Nuxt, Builder } = require('nuxt')
const app = express()

const api = require('./api')
const socket = require('./socket')

const host = process.env.HOST
const port = process.env.PORT

app.set('port', port)

// Listen the server
const server = app.listen(port, host)
const io = require('socket.io').listen(server)

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

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

  console.log('Server listening on http://' + host + ':' + port) // eslint-disable-line no-console

}
start()

// Online users list by country
app.locals.onlineUsers = {};

// Users who is searching partners
app.locals.searchingUsers = {}

socket.start(io, app)
app.use('/api', api)

module.exports = app

这是我的nuxt.config.js

require('dotenv').config()

const pkg = require('./package')

module.exports = {
  mode: 'universal',
  debug: true,
  serverMiddleware: [
    { path: '/api', handler: '~/server/index.js' }
  ],

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: 'http://chateg.com/favicon.ico' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Fredoka+One|Montserrat:200,400,500,700,800&subset=cyrillic' }
    ]
  },

  /*
  ** Customize the progress-bar color
  */
  loading: false,

  /*
  ** Global CSS
  */
  css: [
    '@/assets/scss/main.scss'
  ],

  /*
  ** Router middlewares
  */
  router: {
    middleware: 'i18n'
  },

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    { src: '~/plugins/i18n.js', ssr: true },
    { src: '~/plugins/vue-select.js', ssr: false },
    { src: '~/plugins/vue-flux.js', ssr: false },
    { src: '~plugins/ga.js', ssr: false },
    { src: '~plugins/socket.io.js', ssr: false }
  ],

  /*
  ** Generate dynamic routes
  */
  generate: {
    routes: [
      '/ru/login',
      '/uz/login',
      '/ru/chat',
      '/uz/chat'
    ]
  },

  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/router',
    '@nuxtjs/sitemap',
    ['@nuxtjs/component-cache', {
      max: 10000,
      maxAge: 1000 * 60 * 60
    }],
    ['@nuxtjs/google-analytics', {
      id: 'UA-129371850-1'
    }]
  ],

  /*
  ** Generates sitemap
  */
  sitemap: {
    path: '/sitemap.xml',
    hostname: 'http://chateg.com',
    cacheTime: 1000 * 60 * 15,
    gzip: true,
    generate: false, // Enable me when using nuxt generate
    exclude: [
      '/secret',
      '/admin/**'
    ],
    routes: [
      '/ru/login',
      '/uz/login',
      '/ru/chat',
      '/uz/chat'
    ]
  },

  /*
  ** Axios module configuration
  */
  axios: {
    baseURL: process.env.BASE_URL
  },

  /*
  ** Build configuration
  */
  build: {
    // analyze: true,
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      // config.resolve.alias['vue'] = 'vue/dist/vue.common'

      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}

这是我的server/api/index.js

const express = require('express')
const router = express.Router()
const request = require('request')
const getPostData = require('../middleware/getPostData')
const help = require('../helper')

router.use(getPostData)


router.post('/login', function (req, res) {
    let user = null;

    if (req.body.user) {
        user = req.body.user;
        console.log(user)
    }

    if (!user.sex || !user.partner || !user.country || !user.token) {
        return res.status(400).json({ message: "Something went wrong!" });
    }

    const verifyCaptchaOptions = {
        uri: "https://www.google.com/recaptcha/api/siteverify",
        json: true,
        form: {
            secret: '6Ld4RnQUAAAAAPdZaBbHdginQWteAohILLt1OXuT',
            response: user.token
        }
    }

    request.post(verifyCaptchaOptions, function (err, response, body) {
        if (err) {
            return res.status(500).json({ message: "oops, something went wrong on our side" });
        }

        if (!body.success) {
            return res.status(500).json({ message: body["error-codes"].join(".") });
        }

        //Save the user to the database. At this point they have been verified.
        res.status(201).json({ success: true, user: user });
    });

})

router.get('/get_users', function (req, res) {
    let numberOfOnlineUsers = 0;
    let users = req.app.locals.onlineUsers;

    if (Object.keys(users).length) {
        for (const key in users) {
            if (users.hasOwnProperty(key)) {
                numberOfOnlineUsers += help.countArray(users[key]);
            }
        }
    }

    res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})

router.get('/get_users_from_country', function (req, res) {
    let numberOfOnlineUsers = 0;
    let countryId = 'undefined';
    let users = req.app.locals.onlineUsers;

    if (req.query.countryId) {
        countryId = req.query.countryId;
    }

    if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
        numberOfOnlineUsers = help.countArray(users[countryId]);
    }

    res.status(201).json({ onlineUsers: numberOfOnlineUsers })
})

router.get('/get_males_and_females', function (req, res) {
    let males = 0;
    let females = 0;
    let countryId = 'undefined';
    let users = req.app.locals.onlineUsers;

    if (req.query.countryId) {
        countryId = req.query.countryId;
    }

    if (users.hasOwnProperty(countryId) && users[countryId].length > 0) {
        users[countryId].forEach(item => {
            if (item.sex == 'female') {
                females++;
            } else if (item.sex == 'male') {
                males++;
            }
        })
    }

    res.status(201).json({ males: males, females: females })
})

module.exports = router

我确定配置中与nuxt的serverMiddleware有关的错误会在我评论它时很好,但我无法访问我的API。 请尽量帮助我。我有两天没能解决这个问题。

0 个答案:

没有答案