1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- const { Nuxt, Builder } = require('nuxt')
- const app = require('express')()
- const proxy = require('http-proxy-middleware')
- const cookiejar = require('cookiejar')
- const isProd = (process.env.NODE_ENV === 'production')
- const host = process.env.HOST || '127.0.0.1'
- const port = process.env.PORT || 4444
- process.noDeprecation = true
- app.set('port', port)
- // We instantiate nuxt.js with the options
- const config = require('./nuxt.config.js')
- config.dev = !isProd
- // 请求代理,dev模式下使用,接口服务器如果支持跨域可去掉
- const proxyTable = config.proxyTable
- if (proxyTable) {
- // 本地代理支持localhost、127.0.0.1等不同地址跨域
- app.use((req, res, next) => {
- res.header('Access-Control-Allow-Origin', '*')
- res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,TRACE,OPTIONS,PATCH')
- res.header('Access-Control-Allow-Headers', 'Origin,X-Requested-With,Content-Type,Accept,withCredentials')
- res.header('Access-Control-Allow-Credentials', 'true')
- next()
- })
- if (Array.isArray(proxyTable)) {
- app.use(proxy(proxyTable, {
- target: config.env.baseUrl,
- changeOrigin: true,
- logLevel: config.dev ? 'debug' : 'info',
- onProxyRes: (proxyRes) => {
- const setCookieHeaders = proxyRes.headers['set-cookie'] || []
- const modifiedSetCookieHeaders = setCookieHeaders
- .map(str => new cookiejar.Cookie(str))
- .map(cookie => {
- cookie.path = '/'
- return cookie
- })
- .map(cookie => cookie.toString())
- proxyRes.headers['set-cookie'] = modifiedSetCookieHeaders
- }
- }))
- } else {
- Object.keys(proxyTable).forEach((context) => {
- let options = proxyTable[context]
- if (typeof options === 'string') {
- options = { target: options }
- }
- app.use(proxy(context, options))
- })
- }
- // axios use proxy url
- config.env.proxyUrl = '/'
- }
- const nuxt = new Nuxt(config)
- // Render every route with Nuxt.js
- app.use(nuxt.render)
- // Build only in dev mode with hot-reloading
- if (config.dev) {
- new Builder(nuxt).build()
- .then(listen)
- .catch((error) => {
- console.error(error)
- process.exit(1)
- })
- }
- else {
- listen()
- }
- function listen() {
- // Listen the server
- app.listen(port)
- console.log(`\n Server listening on ${host}:${port}, at ${new Date().toLocaleString()} \n to api ${config.env.baseUrl}`)
- }
|