Koajs:如何检查当前连接是否通过 https?

Koajs: How to check current connection is over https or not?

我正在使用 koajs,我有一个如下所示的路由器,我想检测用户是否通过 https 请求,我该如何实现?

router.get('/video', function(next){
  if(request is over https) {
      this.body = yield render('/video', {});
  } else {
      this.redirect('https://example.com/video');
  }
});

您可以使用附加到上下文的 request 对象的 secure。它也被别名为 ctx 本身。

Koa v1:

router.get('/video', function *(next) {
  if (this.secure) {
    // The request is over https
  }
})

Koa v2:

router.get('/video', async (ctx, next) => {
  if (ctx.secure) {
    // The request is over https
  }
})

ctx.secure 等同于检查 ctx.protocol === "https"

Koa website docs 中都提到了这些,我绝对建议您在遇到与 Koa 相关的问题时首先查看那里。