server.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const { Nuxt, Builder } = require('nuxt')
  2. const app = require('express')()
  3. const proxy = require('http-proxy-middleware')
  4. const cookiejar = require('cookiejar')
  5. const isProd = (process.env.NODE_ENV === 'production')
  6. const host = process.env.HOST || '127.0.0.1'
  7. const port = process.env.PORT || 4444
  8. process.noDeprecation = true
  9. app.set('port', port)
  10. // We instantiate nuxt.js with the options
  11. const config = require('./nuxt.config.js')
  12. config.dev = !isProd
  13. // 请求代理,dev模式下使用,接口服务器如果支持跨域可去掉
  14. const proxyTable = config.proxyTable
  15. if (proxyTable) {
  16. // 本地代理支持localhost、127.0.0.1等不同地址跨域
  17. app.use((req, res, next) => {
  18. res.header('Access-Control-Allow-Origin', '*')
  19. res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,TRACE,OPTIONS,PATCH')
  20. res.header('Access-Control-Allow-Headers', 'Origin,X-Requested-With,Content-Type,Accept,withCredentials')
  21. res.header('Access-Control-Allow-Credentials', 'true')
  22. next()
  23. })
  24. if (Array.isArray(proxyTable)) {
  25. app.use(proxy(proxyTable, {
  26. target: config.env.baseUrl,
  27. changeOrigin: true,
  28. logLevel: config.dev ? 'debug' : 'info',
  29. onProxyRes: (proxyRes) => {
  30. const setCookieHeaders = proxyRes.headers['set-cookie'] || []
  31. const modifiedSetCookieHeaders = setCookieHeaders
  32. .map(str => new cookiejar.Cookie(str))
  33. .map(cookie => {
  34. cookie.path = '/'
  35. return cookie
  36. })
  37. .map(cookie => cookie.toString())
  38. proxyRes.headers['set-cookie'] = modifiedSetCookieHeaders
  39. }
  40. }))
  41. } else {
  42. Object.keys(proxyTable).forEach((context) => {
  43. let options = proxyTable[context]
  44. if (typeof options === 'string') {
  45. options = { target: options }
  46. }
  47. app.use(proxy(context, options))
  48. })
  49. }
  50. // axios use proxy url
  51. config.env.proxyUrl = '/'
  52. }
  53. const nuxt = new Nuxt(config)
  54. // Render every route with Nuxt.js
  55. app.use(nuxt.render)
  56. // Build only in dev mode with hot-reloading
  57. if (config.dev) {
  58. new Builder(nuxt).build()
  59. .then(listen)
  60. .catch((error) => {
  61. console.error(error)
  62. process.exit(1)
  63. })
  64. }
  65. else {
  66. listen()
  67. }
  68. function listen() {
  69. // Listen the server
  70. app.listen(port)
  71. console.log(`\n Server listening on ${host}:${port}, at ${new Date().toLocaleString()} \n to api ${config.env.baseUrl}`)
  72. }