alioth/before/hoto/reference/graphResource2/test/koa-send方法.md
2025-05-30 09:18:01 +08:00

47 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

`koa-send` 是一个 Koa 中间件,用于发送文件或目录响应给客户端。它提供了一种简单的方式来处理静态文件的发送。下面是一个使用示例:
```javascript
const Koa = require('koa');
const send = require('koa-send');
const app = new Koa();
app.use(async (ctx, next) => {
// 使用 koa-send 发送文件
await send(ctx, 'path/to/file.txt');
});
app.listen(3000, () => {
console.log('Server started on 3000');
});
```
在上面的示例中,`koa-send` 中间件用于处理所有的请求,并将文件 `path/to/file.txt` 发送给客户端。
除了发送单个文件外,你还可以发送整个目录:
```javascript
app.use(async (ctx, next) => {
// 使用 koa-send 发送目录
await send(ctx, 'path/to/directory');
});
```
这将发送指定目录下的文件,可以在请求的 URL 中指定特定的文件。
`koa-send` 还提供了一些选项,用于设置发送文件时的行为。例如,你可以指定根目录、设置缓存控制头、设置内容类型等。以下是一个使用选项的示例:
```javascript
app.use(async (ctx, next) => {
await send(ctx, 'path/to/file.txt', {
root: 'public', // 设置根目录
maxage: 1 * 24 * 60 * 60 * 1000, // 设置缓存时间
immutable: true, // 设置不可变性immutable
contentType: 'text/plain' // 设置内容类型
});
});
```
在上面的示例中,我们将根目录设置为 `public`,将缓存时间设置为 1 天,启用不可变性,并设置内容类型为 `text/plain`
通过这些选项,你可以对发送的文件进行更细致的控制。更多的选项和详细的使用方式可以查看 `koa-send` 的文档。