start.js内容如下:
1 2 3 4 5 6 7 8 | require( 'babel-core/register' )({ 'presets' : [ 'stage-3' , 'latest-node' ] }) require( 'babel-polyfill' ) require( './server' ) |
但是控制台报错404
package.json中的配置:
1 2 3 4 5 6 7 | "scripts" : { "dev" : "nodemon -w ./server -w ./start.js --exec node ./start.js" , "build" : "nuxt build && backpack build" , "start" : "cross-env NODE_ENV=production node build/main.js" , "precommit" : "npm run lint" , "lint" : "eslint --ext .js,.vue --ignore-path .gitignore ." } |
server下的index.js内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import Koa from 'koa' import { Nuxt, Builder } from 'nuxt' import R from 'ramda' import { resolve } from 'path' // Import and Set Nuxt.js options let config = require( '../nuxt.config.js' ) config.dev = !(process.env === 'production' ) const r = path => resolve(__dirname,path) const host = process.env.HOST || '127.0.0.1' const port = process.env.PORT || 3000 const MIDDLEWARES = [ 'router' ]; class Server { constructor () { this .app = new Koa(); this .useMiddleWares( this .app)(MIDDLEWARES); } useMiddleWares (app) { return R.map(R.compose( R.map(i => i(app)), require, i => `${r( './middlewares' )}/${i}`) ) } async start () { // Instantiate nuxt.js const nuxt = new Nuxt(config) // Build in development if (config.dev) { const builder = new Builder(nuxt) builder.build(). catch (e => { console.error(e) // eslint-disable-line no-console process.exit(1) }) } this .app.use(ctx => { ctx.status = 200 // koa defaults to 404 when it sees that status is unset return new Promise((resolve, reject) => { ctx.res.on( 'close' , resolve) ctx.res.on( 'finish' , resolve) nuxt.render(ctx.req, ctx.res, promise => { // nuxt.render passes a rejected promise into callback on error. promise.then(resolve). catch (reject) }) }) }) this .app.listen(port, host) console.log( 'Server listening on ' + host + ':' + port) // eslint-disable-line no-console } } const app = new Server(); app.start(); |
登录后可查看更多问答,登录/注册