在nuxt项目中新建文件夹 /server 在server中新建app.js
1.首先package.json中安装
koa
koa-body
koa-router
koa-static
npm install koa koa-body koa-router koa-static -S
2.执行 npm install -g nodemon 使用nodemon进行开发管理
3.app.js 配置如下
const Koa = require('koa')
const body = require('koa-body')
const path = require('path')
const app = new Koa()
const { Nuxt, Builder } = require('nuxt')
const nuxtConfig = require('../nuxt.config.js')app.use(body({formidable: {keepExtensions: true,maxFieldsSize: 500 * 1024 * 1024, // 文件上传大小hash: 'md5',onFileBegin: (name, file) => { // 文件上传前的设置},},multipart: true,
}))global.isDev = false
const env = app.env
if (env == "development") { //坑点 设置环境的时候 注意空格global.host = 'http://127.0.0.1:4000/'global.isDev = true
} else if (env == "production") {global.host = 'http://xx.xxx.com/'
}//拦截静态资源 开始
const static = require('koa-static')
const staticpath = './static/'
app.use(static(path.join(__dirname, staticpath), {immutable: true
}));nuxtConfig.dev = global.isDev
async function start() {const nuxt = new Nuxt(nuxtConfig)const {host = process.env.HOST || '127.0.0.1',port = process.env.PORT || 4000} = nuxt.options.serverif (nuxtConfig.dev) {const builder = new Builder(nuxt)await builder.build() //开发环境下 进行实时nuxt编译} else {await nuxt.ready()}app.on("error", (err, ctx) => {})app.use(async (ctx, next) => {if (/api\//.test(ctx.request.url)) { //如果url中白包含 api/ 判定为 接口为koa2的返回参数渲染await next()} else {//不然使用nuxt的的render渲染ctx.status = 200return new Promise((resolve, reject) => {ctx.res.on('close', resolve)ctx.res.on('finish', resolve)nuxt.render(ctx.req, ctx.res, promise => {promise.then(resolve).catch(reject)})})}})const route = require("./routes/index") //所有koa2 route的配置加载route(app)let server = app.listen(port, host)server.timeout = 5 * 60 * 1000 //超时设置
}start()
4.package.json中配置
"scripts": {"dev": "nuxt","build": "nuxt build","start": "nuxt start","serverstart": "set NODE_ENV=production&&nodemon server/app.js", //新增 生产测试"serverdev": "set NODE_ENV=development&&nodemon server/app.js",//新增 开发环境"server": "pm2 start ecosystem.config.js --env production", //新增发布模式"generate": "nuxt generate"}
ecosystem.config.js文件配置请参考 pm2官网的相关配置