Koa-Static 该换换了吧 试试 Awesome-Static

其实还是得按自个儿的需求来。

koa-static 有啥问题么

koa-static是一个非常轻量的koa中间件,能够迅速的搭建起一个静态文件服务器,通常我们把静态文件都放进public,并且通过类似koa-static这样的东西来将我们的public作为静态目录,这样的话,我们就能直接通过根路由进行访问了。

emmmm,扯多了。回到正轨

首先koa-static不能映射到其他的路由上,一般是跟路由,比如访问 public/main.html(假设 public 为静态目录),那么就可以通过 host:port/main.html 进行访问得到 main.html,但是有时候我不想映射到根路由,这时候,koa-static就显得力不从心了。

第二个问题是koa-static只支持GETHEAD两个 HTTP 方法来进行访问,这在大多数场景下是有用的,但是难免会遇到一些特别的场景,比如你想用POST方法来拿到服务器上的静态文件(如果你想)。

awesome-static

吼,所以我做了awesome-staticawesome-statickoa-static一样,都是对 koa-send的一层封装,只不过awesome-staticTypescript编写,对 VSCode 支持良好。

awesome-static扩充了koa-staticoptions,添加了两个字段

  • route
  • allowMethods

route为要映射到的路由,allowMethods是要允许的 HTTP 方法

这两个字段都是可选的,route 的默认值就是根路由,allowMethods 的默认值为 HEADGET ,所以你能像使用 koa-static 一样的使用 awesome-static

看一下使用方法

const Koa = require('koa');
const app = new Koa();
const { AwesomeStatic } = require('awesome-static');

app.use(AwesomeStatic('public'));

app.listen(8888);

public 下有一个 html 文件,下面是 public 的目录结构

public
└── main.html

在启动服务器后就能通过http://localhost:8888/main.html进行访问了

现在来配置一下 route

const Koa = require('koa');
const app = new Koa();
const { AwesomeStatic } = require('awesome-static');

app.use(AwesomeStatic('public', {
    route:"static"
}));

app.listen(8888);

配置了 routestatic 那么现在访问 main.html 就需要访问http://localhost:8888/static/main.html

如果再配置一下 allowMethods ,来设置一下允许的 HTTP 方法,让它只能通过POST 来访问

const Koa = require('koa');
const app = new Koa();
const { AwesomeStatic } = require('awesome-static');

app.use(AwesomeStatic('public', {
    route:"static",
    allowMethods:["POST"]
}));

app.listen(8888);

现在再通过 http://localhost:8888/static/main.html 就会去 404 了~

来模拟一个 POST 请求

curl http://localhost:8888/static/main.html -X POST

Output:

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

Github

https://github.com/HaoDaWang/awesome-static
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值