记录如何用koa实现一个简易静态资源服务器
这里仅以图片静态服务为例。
根目录下public文件夹下的内容为图片资源
# 安装依赖
- koa-static
- path
# 主程序代码
server.js
const Koa = require('koa')
const app = new Koa()
const path = require('path')
// 静态资源
app.use(require('koa-static')(path.join(__dirname) + '/public'))
app.use(async (ctx) => {
ctx.body = 'static file server'
})
app.listen(3001, () => {
console.log('build success')
})
package.json
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.11.0",
"koa-static": "^5.0.0",
"path": "^0.12.7"
}
}
# 启动服务
node app.js
访问public下的图片资源
⬇️
localhost:3001/[图片名称].jpg