Express’s connection to Koa

Express and Koa are the brainchild of TJ Holowaychuk. Express is a Web application development framework based on node. js platform. Koa, on the other hand, is an upgrade to Express: Koa started out just as Nodejs introduced the async/await syntax. Koa adopted this new syntax feature, discarded callback functions, and implemented a lightweight and elegant Web backend framework. Both are developed in a middleware approach and the apis are basically the same.

Differences between Express and Koa

1. Middleware model

The middleware model of Express is linear, while the middleware model of Koa is U-shaped, which can also be called onion model construction middleware.

  • ExpressExamples of linear models:
const express = require("express");
const app = express();
const port = 3000;

app.use((req, res, next) = > {
  res.write("hello");
  next();
});
app.use((req, res, next) = > {
  res.set("Content-Type"."text/html; charset=utf-8");
  next();
});
app.use((req, res, next) = > {
  res.write("world");
  res.end();
});
app.listen(3000);
Copy the code
  • KoaExample of onion model:
import * as Koa from "koa";
const app = new Koa();
app.use(async (ctx, next) => {
  ctx.body = "hello";
  await next();
  ctx.body += "world";
});
app.use(async (ctx) => {
  ctx.set("Content-Type"."text/html; charset=utf-8");
});
app.listen(3000);
Copy the code

As you can see, Express does the same thing one step further than Koa.

2. Asynchronous mode

  • ExpressAsynchronous functions are implemented through callbacks, which can easily be written in multiple callbacks and middleware.
/ / express way
app.get("/test".function (req, res) {
  fs.readFile("/file1".function (err, data) {
    if (err) {
      res.status(500).send("read file1 error");
    }
    fs.readFile("/file2".function (err, data) {
      if (err) {
        res.status(500).send("read file2 error");
      }
      res.type("text/plain");
      res.send(data);
    });
  });
});
Copy the code
  • Koathroughgeneratorasync/awaitUsing synchronous writing to handle asynchrony is significantly better thancallbackpromise.
app.use(async (ctx, next) => {
  await next();
  var data = await doReadFile();
  ctx.response.type = "text/plain";
  ctx.response.body = data;
});
Copy the code

3. Catch errors

  • ExpressContinue to useNode.jsError-FirstThe first parameter iserrorObject) to catch errors.
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});
Copy the code
  • Koausetry/catchTo catch errors.
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (error) {
    if (error.errorCode) {
      console.log("Exception caught");
      return(ctx.body = errror.msg); }}});Copy the code

4. Response mechanism

  • ExpressImmediate response (res.json/res.send), the upper layer cannot define other processes.
  • KoaMiddleware responds after execution (ctx.body = xxx), each layer can do its own processing of the response

conclusion

The difference between Express Koa
Middleware model Linear model The onion model
asynchronous Based on the callback function Based on the async/await
Capture the error Error – the First mode Use try/catch
The response mechanism The response immediately The middleware does not respond until the execution is complete
Integrated into degrees High degree of integration, with part of the middleware Low integration, no middleware bundled