Appearance
主体限制中间件
¥Body Limit Middleware
Body Limit Middleware 可以限制请求正文的文件大小。
¥The Body Limit Middleware can limit the file size of the request body.
此中间件首先使用请求中的 Content-Length
标头的值(如果存在)。如果未设置,它将读取流中的主体,并在其大于指定的文件大小时执行错误处理程序。
¥This middleware first uses the value of the Content-Length
header in the request, if present. If it is not set, it reads the body in the stream and executes an error handler if it is larger than the specified file size.
导入
¥Import
ts
import { Hono } from 'hono'
import { bodyLimit } from 'hono/body-limit'
用法
¥Usage
ts
const app = new Hono()
app.post(
'/upload',
bodyLimit({
maxSize: 50 * 1024, // 50kb
onError: (c) => {
return c.text('overflow :(', 413)
},
}),
async (c) => {
const body = await c.req.parseBody()
if (body['file'] instanceof File) {
console.log(`Got file sized: ${body['file'].size}`)
}
return c.text('pass :)')
}
)
选项
¥Options
required maxSize:number
你想要限制的文件的最大文件大小。默认为 100 * 1024
- 100kb
。
¥The maximum file size of the file you want to limit. The default is 100 * 1024
- 100kb
.
optional onError:OnError
如果超出指定的文件大小,则调用错误处理程序。
¥The error handler to be invoked if the specified file size is exceeded.
与 Bun 一起使用以处理大量请求
¥Usage with Bun for large requests
如果明确使用 Body Limit Middleware 来允许请求主体大于默认值,则可能需要相应地更改 Bun.serve
配置。撰写本文时、Bun.serve
的默认请求正文限制为 128MiB。如果你将 Hono 的 Body Limit Middleware 设置为大于该值,你的请求仍将失败,此外,中间件中指定的 onError
处理程序将不会被调用。这是因为 Bun.serve()
会在将请求传递给 Hono 之前将状态代码设置为 413
并终止连接。
¥If the Body Limit Middleware is used explicitly to allow a request body larger than the default, it might be necessary to make changes to your Bun.serve
configuration accordingly. At the time of writing, Bun.serve
's default request body limit is 128MiB. If you set Hono's Body Limit Middleware to a value bigger than that, your requests will still fail and, additionally, the onError
handler specified in the middleware will not be called. This is because Bun.serve()
will set the status code to 413
and terminate the connection before passing the request to Hono.
如果要使用 Hono 和 Bun 接受大于 128MiB 的请求,则还需要为 Bun 设置限制:
¥If you want to accept requests larger than 128MiB with Hono and Bun, you need to set the limit for Bun as well:
ts
export default {
port: process.env['PORT'] || 3000,
fetch: app.fetch,
maxRequestBodySize: 1024 * 1024 * 200, // your value here
}
或者,取决于你的设置:
¥or, depending on your setup:
ts
Bun.serve({
fetch(req, server) {
return app.fetch(req, { ip: server.requestIP(req) })
},
maxRequestBodySize: 1024 * 1024 * 200, // your value here
})