Koa -static middleware
There are three possible responses to a Web HTTP request:
- Access files, such as: JS, CSS, PNG, JPG, GIF, etc
- Accessing a static directory
- Resource not found (HTTP 404)
In the project, like some static file processing, Koa also wanted off-the-shelf modules, saving us many of the steps we needed to read files from the local directory ourselves.
The installation
npm install koa-static
Copy the code
or
yarn add koa-static
Copy the code
use
Koa-static is simple to use, and the core code is:
const static_ = require('koa-static')
const path = require('path')
var app = new Koa();
app.use(static_(
path.join(__dirname, './static')))Copy the code
The complete sample code is as follows:
const Koa = require('koa');
const Router = require('koa-router');
const static_ = require('koa-static')
const path = require('path')
var app = new Koa();
var router = new Router();
app.use(static_(
path.join(__dirname, './static')
))
router.get('/'.(ctx, next) = > {
ctx.body = 'home'
});
router.get('/list'.(ctx, next) = > {
ctx.body = 'list'
})
router.get('/api'.(ctx, next) = > {
let res = {hello: 'world'}
ctx.set("Content-Type"."application/json")
ctx.body = JSON.stringify(res)
})
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000)
Copy the code
I created a new static directory under the current js execution directory, and created a new file named demo.js under the static directory, and added the following contents:
console.log('hello james')
Copy the code
Start the project, we visit: http://localhost:3000/demo.js, you will see the browser will respond as follows:
console.log('hello james')
Copy the code