在线试读

get_product_contenthtml

5.4.1  简易版koa-json插件开发(视频演示)

在5.3.4节的示例项目中,打开服务器并访问http://localhost:3000/,后端路由接收到HTTP请求,然后调用对应的模板文件,将其转化为HTML字符串并响应给浏览器。接下来将介绍前端发起Ajax请求,后端接口返回JSON格式数据的处理方式。

在实际的项目开发中,使用工具查看HTTP请求过程,若返回的页面响应头信息中指定了content-type: text/html,则浏览器会把字符串渲染成HTML页面。HTTP请求的整个过程中所传输的数据,本身没有任何特定的格式或形态,但客户端在接收数据时,会按照MIME Type指定的方式去处理。在此基础之上,简易版的koa-json中间件的开发思路呼之欲出,只需把数据挂载到响应体body上,同时告知客户端数据类型是JSON,客户端就会按照JSON格式来解析了。关键代码如下:

ctx.set("Content-Type", "application/json");

ctx.body = JSON.stringify(json);

 

读者可以进一步尝试把上面的代码提取为中间件,代码如下:

01       module.exports = () => {

02              function render(json) {

03                       this.set("Content-Type", "application/json");

04                      this.body = JSON.stringify(json);

05           }

06              return async (ctx, next) => {

07                   ctx.send = render.bind(ctx);

08                   await next();

09               }

10       }

 

上述中间件被调用时,将会在上下文对象上扩展send函数,并转移控制权。send函数的作用是将需要处理的JSON对象转化为字符串,并指定类型为application/json。接下来使用中间件,代码如下:

ctx.send({

        status: 'success',

        data: 'hello ikcmap'

})

 

为了使项目便于维护,建议读者将所有的中间件独立出来进行管理。

新增middleware目录用来存放所有的中间件。此目录下有index.js文件和项目中需要用到的自定义中间件,项目结构如下:

01   ├── controller/

02   │     ├── home.js

03   ├── service/

04   │     ├── home.js

05   ├── middleware/

06   │     ├── mi-send/

07   │         ├── index.js

08   │     ├── index.js

09   ├── views/

10   │     ├── common/

11   │         ├── header.html

12   │         ├── footer.html

13   │         ├── layout.html

14   │         ├── layout-home.html

15   │     ├── home/

16   │         ├── index.html

17   │         ├── login.html

18   │         ├── success.html

19   ├── public/

20   │     ├── home/

21   │         ├── main.css

22   ├── app.js

23   ├── router.js

 

扩展完成后,把简易版的koa-json迁移到middleware/mi-send/index.js文件中,接下来修改现有代码中的调用方法。

文件middleware/index.js用来集中调用所有的中间件,代码如下:

01        const path = require('path');

02       const bodyParser = require('koa-bodyparser');

03       const nunjucks = require('koa-nunjucks-2');

04        const staticFiles = require('koa-static');

05       const miSend = require('./mi-send');

06        module.exports = (app) => {

07              app.use(staticFiles(path.resolve(__dirname, "../public")));

08               app.use(nunjucks({

09                   ext: 'html',

10                   path: path.join(__dirname, '../views'),

11                       nunjucksConfig: {

12                       trimBlocks: true

13                   }

14              }));

15               app.use(bodyParser());

16              app.use(miSend());

17       }

 

修改app.js,增加对中间件的引用,代码如下:

01     const Koa = require('koa');

02        const app = new Koa();

03       const router = require('./router');

04        const middleware = require('./middleware');

05       middleware(app);

06        router(app);

07        app.listen(3000, () => {

08            console.log('server is running at http://localhost:3000');

09        });

 

此时的项目结构更加清晰,项目文件说明如下:

?  router.js:注册项目中所有的路由。

?  middleware:集中管理项目中用到的所有中间件,包括自定义中间件。

?  controller:路由请求对应的处理函数。

?  service:提供controller逻辑中需要用到的底层数据。

?  views:集中管理所有的视图模板文件。

?  public:集中管理所有的静态资源。

?  app.js:项目入口文件。

本节在线视频地址为https://camp.qianduan.group/koa2/2/2/1,二维码: