Koa 简版服务

332 阅读1分钟

1.创建文件夹:

mkdir koa

2.初始化package.json:

cd koa
yarn init -y

3.新建文件:

touch index.html
touch index.js

4.安装package:

yarn add koa @koa/router koa-body
yarn add nodemon --dev

5.配置 package.json scripts:

"scripts": {
    "start": "nodemon index.js"
}

6.启动服务:

yarn start

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Koa</title>
</head>
<body>
  <h1>Hello, Koa!</h1>
</body>
</html>

index.js:

const Koa = require('koa');
const koaBody = require('koa-body');
const Router = require('@koa/router');
const fs = require('fs');

const app = new Koa();
const router = new Router();

app.use(koaBody());

router.get('/', async (ctx) => {
  ctx.type = 'text/html;charset=utf-8';
  ctx.body = fs.readFileSync('./index.html');
});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(5000, () => {
  console.log('服务已启动: http://localhost:5000');
});