- ArthurSlog
- SLog-4
Year·1
Guangzhou·China
- July 11th 2018
![]()
梦想是锁不住的
开发环境MacOS(High Sierra 10.13.5)
老规则,首先准备我们需要的信息Koa官方手册、Koa中间件 和 我们要用到的中间件Koa-static
准备的信息差不多,现在切换至桌面路径
cd ~/Desktop
- 创建一个文件夹node_koa_learningload
mkdir node_koa_learningload
- 切换路径到新建的文件夹下
cd node_koa_learningload
- 使用npm初始化node环境,一路enter键完成初始化
npm init
- 使用npm安装koa和koa-static
sudo npm install koa koa-static
- 参考Koa-static说明手册,我们在当前路径下编写index.js和index.html两份文件
index.js
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
// $ GET /package.json
app.use(serve('.'));
// $ GET /hello.txt
app.use(serve('test/fixtures'));
// or use absolute paths
app.use(serve(__dirname + '/test/fixtures'));
app.listen(3000);
console.log('listening on port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ArthurSlog</title>
</head>
<body>
<h1>The static web server by ArthurSlog</h1>
</body>
</html>
- index.js是官方栗子,有三种路由方法,我们来分析一下:
- 路由当前路径,默认的路由文件名是index.html
// $ GET /package.json
app.use(serve('.'));
- 使用相对路径作为路由,默认的路由文件名是index.html
// $ GET /hello.txt
app.use(serve('test/fixtures'));
- 使用绝对路径作为路由,默认的路由文件名是index.html
// or use absolute paths
app.use(serve(__dirname + '/test/fixtures'));
- 在这里,我们直接用第一种方式,最终的代码为
index.js
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
// $ GET /package.json
app.use(serve('.'));
app.listen(3000);
console.log('listening on port 3000');
- Ok,现在启动静态web服务器
node index.js
打开浏览器测试一下,地址127.0.0.1:3000
至此,我们使用koa和中间件koa-static实现了一个静态web服务器,恭喜。
欢迎关注我的微信公众号 ArthurSlog
![]()

本文在MacOS环境下,通过KOA框架和koa-static中间件,详细介绍了如何创建并启动一个静态Web服务器。首先,初始化Node环境,然后安装所需依赖。接着,编写index.js文件设置路由,并创建index.html。最后,运行服务器并在浏览器中验证效果。
317

被折叠的 条评论
为什么被折叠?



