ITPub博客

首页 > IT职业 > IT图书 > 入门基于node平台的web开发框架koa(2)koa服务环境搭建

入门基于node平台的web开发框架koa(2)koa服务环境搭建

IT图书 作者:jn_fjd 时间:2021-09-09 08:53:55 0 删除 编辑

在实际开发过程中,往往不可能像上篇文章一样,将各种代码写在同一个文件里面,应该通过一定的代码结构设计来规范开发。

项目的结构一般有一下几个部分

图片描述

入口文件

const koa = require('koa')
const path = require('path') // node的path模块,用于处理文件路径
const app = new koa()
const helmet = require('koa-helmet') // 安全头盔
const statics = require('koa-static') // 静态文件插件
const router = require('./routes/routes')
app.use(helmet())
app.use(statics(path.join(__dirname, '../public')))
app.use(router())
app.listen(3000)

通过routes.js文件合并需用引用的代码,执行npm install koa-combine-routers -s

const combineRoutes = require('koa-combine-routers')
const aroutes = require('./aRouter')
const broutes = require('./bRouter')
/** 
*  通过引入koa-combine-routers插件,将不同的路由逻辑进行合并,再在入口文件统一执行 
*/
module.exports = combineRoutes(  aroutes,  broutes)

图片描述

function a (ctx) {  
ctx.body = {    
    "code": 200,    
    "message": "hello from a"  
}}
module.exports = { a }

npm install koa-helmet -s // 安全插件,添加安全头部

图片描述

npm install koa-static -s // 处理静态资源

图片描述

这样一个简单的koa结构的搭建完成

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3813/viewspace-2797864/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-27

  • 博文量
    0
  • 访问量
    443