How to handle static files in koa

For a standard WEB server, in addition to processing the program js code that needs to be executed, we may need to download the corresponding client static resources, such as: pictures, css files, client js files and corresponding html files, then How should we deal with it in koa? There are two main modules referenced here. One is koa-static and the other is path. Here we need to install it before using it. If it is not installed, an error will occur. Therefore, execute
npm install koa-static
npm install path before using it.

const statics = require('koa-static')
const path = require('path')

app.use(statics(
  path.join(__dirname, staticPath)
))

Note: path is mainly used to handle path-related methods, and __dirname represents the directory where the current execution file is located. This is mainly to register the middleware koa-static to process static files, and the parameter of the middleware is the directory location where the static files are to be stored.
We enter http://localhost:3000/azh.jpg in the browser and the actual output is the azh.jpg picture under the static directory. Here we have a few points to pay attention to.
1. We can create other directories under the static directory, such as: images, css, js and so on.
2. When we enter the url in the browser, do not include static in the url, because it will automatically go to the static directory to find the content with the extension name static text, so the correct url is http://localhost:3000/azh. jpg instead of http://localhost:3000/static/azh.jpg
3. If the file cannot be found in static, it will be passed to the middleware for processing. The key here is the location of each middleware.

Guess you like

Origin blog.csdn.net/weixin_36557877/article/details/129304041