Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Created November 10, 2020 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms/c4f28e7d0735866d38a1af66235842bf to your computer and use it in GitHub Desktop.
Save xgqfrms/c4f28e7d0735866d38a1af66235842bf to your computer and use it in GitHub Desktop.
koa-https-server

koa-https-server

{
  "name": "koa-server",
  "version": "1.0.0",
  "description": "koa https server",
  "main": "src/index.js",
  "scripts": {
    "env": "export HTTPS=true && SSL_CRT_FILE=cert.pem && SSL_KEY_FILE=key.pem",
    "dev": "node ./src/index.js",
    "app": "yarn env && yarn auto",
    "auto": "yarn open && ./node_modules/nodemon/bin/nodemon.js ./src/index.js",
    "start": "./node_modules/pm2/bin/pm2 start src/index.js",
    "open": "open http://localhost:3000",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "koa"
  ],
  "author": "xgqfrms",
  "license": "MIT",
  "dependencies": {
    "koa": "^2.13.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.6",
    "pm2": "^4.5.0"
  }
}
@xgqfrms
Copy link
Author

xgqfrms commented Nov 10, 2020

@xgqfrms
Copy link
Author

xgqfrms commented Nov 10, 2020

KOA

https://koajs.com/

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

@xgqfrms
Copy link
Author

xgqfrms commented Nov 10, 2020

Koa middleware cascade

中间件,洋葱模型

const Koa = require('koa');
const app = new Koa();

// logger

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// response

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment