• ArthurSlog

  • SLog-4

  • 1 Year,

  • Through China,

  • July 11th 2018

Scan the QR code on wechat and follow my official account

Dreams can’t be locked

Development Environment MacOS(High Sierra 10.13.5)

  • Old rule, first prepare the information we need Koa official manual, Koa middleware and the middleware we will use koA-static

  • You have the same information. Now switch to the desktop path

cd ~/Desktop

  • Create a folder node_KOA_LearningLoad

mkdir node_koa_learningload

  • Switch to the new folder

cd node_koa_learningload

  • Use NPM to initialize the Node environment, press Enter to complete the initialization

npm init

  • Install KOA and KOA-static using NPM

sudo npm install koa koa-static

  • With reference to the KOA-static instruction manual, we write two files index.js and index. HTML under the current path

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');
Copy the code

index.html


      
<html>
<head>
<meta charset="utf-8">
<title>ArthurSlog</title>
</head>
<body>

<h1>The static web server by ArthurSlog</h1>

</body>
</html>
Copy the code
  • Index.js is the official routing method, there are three methods, let’s analyze:
  1. Route Current path. The default route file name is index.html
// $ GET /package.json
app.use(serve('. '));
Copy the code
  1. Using relative paths as routes, the default route file name is index.html
// $ GET /hello.txt
app.use(serve('test/fixtures'));
Copy the code
  1. Using absolute paths as routes, the default route file name is index.html
// or use absolute paths
app.use(serve(__dirname + '/test/fixtures'));
Copy the code
  • In this case, let’s go straight to the first method, and the final code is zero

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');
Copy the code
  • Ok, now start the static Web server

node index.js

  • Open your browser and test it at 127.0.0.1:3000

  • So far, we have implemented a static Web server using KOA and the middleware koA-Static. Congratulations.

Please follow my wechat account ArthurSlog

Scan the QR code on wechat and follow my official account

If you like my article, please like it and leave a comment

thank you