使用KOA处理 npm i koa -S // node端的服务框架
位置:server/server.js新建
const Koa = require('koa')
const send = require('koa-send')
const path = require('path')
const pageRouter = require('./routers/dev-ssr')
const app = new Koa()
const isDev = process.env.NODE_ENV === 'development'
app.use(async (ctx, next) => { //koa中间键,抓取错误
try {
console.log(`request with path ${ctx.path}`)
await next()
} catch (err) {
console.log(err)
ctx.status = 500
if (isDev) {
ctx.body = err.message
} else {
ctx.body = "please try it later"
}
}
})
app.use(async (ctx, next) => {
if (ctx.path === '/favicon.ico') {
await send(ctx, '/favicon.ico', {root: path.join(__dirname, '../')})//
} else {
await next()
}
})
app.use(pageRouter.routes()).use(pageRouter.allowedMethods())//既定用法,不用深究
const HOST = process.env.HOST || '0.0.0.0'
const PORT = process.env.PORT || 3333
app.listen(PORT, HOST, () => {
console.log(`server is listening on ${HOST}:${PORT}`)
})复制代码