Slog4_使用後端框架KOA實現靜態web服務器

  • ArthurSlog
  • SLog-4
  • Year·1
  • Guangzhou·China
  • July 11th 2018

關注微信公衆號「ArthurSlog」

開發環境MacOS(High Sierra 10.13.5)

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

index.jsnode

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.htmlgit

<!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是官方栗子,有三種路由方法,咱們來分析一下:
  1. 根據node工程的配置文件package.json裏指定的入口點「main」決定路由
// $ GET /package.json
app.use(serve('.'));
  1. 使用相對路徑做爲路由,默認的路由文件由package.json裏的入口點「main」決定
// $ GET /hello.txt
app.use(serve('test/fixtures'));
  1. 使用絕對路徑做爲路由,默認的路由文件由package.json裏的入口點「main」決定
// or use absolute paths
app.use(serve(__dirname + '/test/fixtures'));
  • 在這裏,咱們直接用第一種方式,最終的代碼爲

index.jsgithub

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

關注微信公衆號「ArthurSlog」

若是你喜歡個人文章 歡迎點贊 留言

謝謝

相關文章
相關標籤/搜索