index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const Koa = require('koa')
  2. const cors = require('koa2-cors');
  3. const consola = require('consola')
  4. const { Nuxt, Builder } = require('nuxt')
  5. const router = require('./routes/index');
  6. const app = new Koa()
  7. // routes
  8. app.use(router().routes(), router().allowedMethods());
  9. app.use(cors({
  10. origin: 'http://localhost:3000',
  11. // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  12. maxAge: 3600,
  13. credentials: true,
  14. allowMethods: ['GET', 'POST', 'OPTIONS'],
  15. allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  16. }));
  17. // Import and Set Nuxt.js options
  18. const config = require('../nuxt.config.js')
  19. config.dev = app.env !== 'production'
  20. async function start () {
  21. // Instantiate nuxt.js
  22. const nuxt = new Nuxt(config)
  23. const {
  24. host = process.env.HOST || '127.0.0.1',
  25. port = process.env.PORT || 8000
  26. } = nuxt.options.server
  27. await nuxt.ready()
  28. // Build in development
  29. if (config.dev) {
  30. const builder = new Builder(nuxt)
  31. await builder.build()
  32. }
  33. app.use((ctx) => {
  34. ctx.status = 200
  35. ctx.respond = false // Bypass Koa's built-in response handling
  36. ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
  37. nuxt.render(ctx.req, ctx.res)
  38. })
  39. app.listen(port, host)
  40. consola.ready({
  41. message: `Server listening on http://${host}:${port}`,
  42. badge: true
  43. })
  44. }
  45. start()