之前都是将所有的接口请求,都写在了index.js文件里面会特别的冗长。维护起来不方便,所以需要自己配置开发目录结构。

开发目录结构

代码演示

创建一个文件夹 koa-demo ,并执行以下命令

  1. $ cd koa-demo # 进入项目目录
  2. $ npm init -y # nodejs项目初始化
  3. $ npm install -S koa-router koa-body @koa/cors koa-json koa-combine-routers koa-static koa-helmet

创建目录结构如下:
koa-demo
|—-src
|—-api
|—-a.js
|—-b.js
|—-routes
|—-aRouter.js
|—-bRouter.js
|—-routes.js
|—-index.js

/src/api/a.js**

  1. module.exports = function (ctx) {
  2. ctx.body = {
  3. "message": "hello from a!!!"
  4. }
  5. }

/src/api/b.js

  1. module.exports = function (ctx) {
  2. ctx.body = {
  3. "message": "hello from b"
  4. }
  5. }

/src/routes/aRouter.js

  1. const Router = require("koa-router")
  2. const a = require("../api/a")
  3. const router = new Router()
  4. router.get('/a', a)
  5. module.exports = router

/src/routes/bRouter.js

  1. const Router = require("koa-router")
  2. const b = require("../api/b")
  3. const router = new Router()
  4. router.get('/b', b)
  5. module.exports = router

/src/routes/routes.js

  1. // 使用插件(中间件)完成路由的压缩
  2. const combineRoutes = require("koa-combine-routers");
  3. const aroutes = require("./aRouter")
  4. const broutes = require("./bRouter")
  5. module.exports = combineRoutes(
  6. aroutes,
  7. broutes
  8. )

/src/index.js

  1. const koa = require("koa");
  2. const path = require('path');
  3. const app = new koa();
  4. const router = require("./routes/routes");
  5. app.use(router())
  6. app.listen(3000)

运行

  1. node src/index.js

访问不同的路由可对应不同的内容
image.pngimage.png
下面来使用下 koa-static 和 koa-helmet
修改目录结构如下:
koa-demo
|—-src
+|—-public
+|—-logo.png
|—-api
|—-a.js
|—-b.js
|—-routes
|—-aRouter.js
|—-bRouter.js
|—-routes.js
|—-index.js
编辑下 src/index.js

  1. const koa = require("koa");
  2. const path = require('path');
  3. const app = new koa();
  4. // 安全头
  5. const helmet = require("koa-helmet");
  6. // 静态资源
  7. const statics = require("koa-static")
  8. const router = require("./routes/routes");
  9. // 使用安全头
  10. app.use(helmet())
  11. // 静态资源处理
  12. app.use(statics(path.join(__dirname, '../public')))
  13. app.use(router())
  14. app.listen(3000)

运行

  1. node src/index.js

之后访问根据图片名,访问路径就成功了
image.png