Koa is a lightweight web services framework with no built-in middleware, so we need to implement our own middleware or use middleware developed by a third party.

Static service middleware

When writing a server application, are generally used to as static server, node structures, static services please check my previous articles, the express service middleware for static resources can be used to express the static () to do this, then koa how to do? In fact, for a static service, as long as you know the underlying principle of Node, express or KOA applications are based on the underlying principle

steps

  1. Get path ofpathAs a service, you need to provide a root path and a directory of static resources;
  2. Check whether the path provided is a folder, file, or does not exist.
  3. To read the contents of the specified file, set the response header;
  4. Returns the contents of a file to the browser

The code is as follows:

const path = require('path');
const fs = require('fs')
// The mime library is used here to determine the type of file and set the response header
const mime = require('mime');
/** * Get the file name *@param {*} filename 
 * @param {*} root 
 * @returns * /
async function getFileName(filename, root) {
  // Get the full path of the file. Node specifies that the absolute path is a heel path if it starts with \
  const fullName = path.resolve(root, filename.substring(1));
  // Determine whether the current path is a file or folder or does not exist
  try {
    const fsStat = await fs.promises.stat(fullName);
    if (fsStat.isDirectory()) {
      // If it is a directory, the default file needs to be replaced
      const adtFileName = path.join('/index.html');
      return await getFileName(adtFileName, root);
    } else {
      returnfullName; }}catch (error) {
    return null; }}/** * Read the static resource directory *@param {*} root 
 * @returns * /
module.exports = function (root) {
  return async (ctx, next) => {
    if(ctx.method ! = ='GET') {
      await next();
      return;
    }
    const filename = await getFileName(ctx.path, root)
    if(! filename) {// File does not exist
      await next();
      return;
    }
    // Respond to the file according to the file name extension
    const mimeType = mime.getType(filename);
    // Returns a file stream
    ctx.body = fs.createReadStream(filename);
    // Set the file type
    ctx.type = mimeType;
    awaitnext(); }}Copy the code

Manual implementationconnect-history-api-fallbackThe middleware

In a single page application, we use the history mode of the route. When refreshing the browser, we need to go back to the index.html page. How does this middleware implement in KOA? Connect-history-api-fallback has several matching rules:

The rules

` `

  1. Can matchgetrequest
  2. The request ofheaderThe file type of thetext/html
  3. The request is not a redirected request, requestedpathCannot contain,“, because dotted means to request a static resource such as JS, CSS, image, etc

code

module.exports = async function (ctx, next) {
  // Determine if the current request is a GET request, if the request path contains., and if the request header type is an HTML file
  if (ctx.method === "GET" &&
    ctx.headers.accept.includes("text/html") &&
    !ctx.path.includes(".")) {
    ctx.path = '/index.html'
  }
  await next();
}
Copy the code

This place is a small episode, that is, when using a static resource, need to use absolute paths, not using a relative path, or static resource will be wrong, you can open a single page application package path absolute playing on/at the beginning of (premise is that the history model of routing, routing will not use this hash plug-in).

The commonly usedKOAThe middleware

Koa middleware function
@koa/router Official middleware. Learn from thekoa-router

Middleware for processing routing, similar usageexpress.Router
koa-bodyparser Middleware to parse request body, support

X-www-form-urlencoded, application/ JSON format request body
koa-views Middleware for rendering template engines, typically used for traditional server-side rendering
koa-static Middleware for building static resource servers
koa-static-cache Static resource middleware that implements HTTP caching
koa-session The session middleware
koa-jwt Jwt-enabled middleware
koa-compress Middleware that supports gZIP dynamic compression
koa-logger Logging middleware
@koa/cors Official middleware. Middleware that supports CORS across domains
@koa/multer Official middleware, borrowed fromkoa-multer

Middleware for users to process file uploads
koa-connect Convert Express or Connect middleware to KOA middleware
http-proxy-middleware Proxy middleware (this middleware needs to be usedkoa-cennectBefore use)
connect-history-api-fallback Single page application support
This middleware needs to be usedkoa-cennectBefore use)
koa-convert Used to convert older versions of KOA middleware to KOA2 middleware