Skip to content

request | 请求

https://honodev.pages.dev/zh/docs/api/request

请求参数

c.req 是 HonoRequest,文档 :https://honodev.pages.dev/zh/docs/api/request

js
app.get("/entry/:id/comment/:commentId", async (c) => {
  // 获取一个或多个
  const id = c.req.param("id");
  const { id, commentId } = c.req.param();

  // 获取 query
  const page = c.req.query("page");
  // 获取所有query 参数
  const query = c.req.query();

  return c.text(`You want see ${page} of ${id}`);
});

更多路径参数:https://honodev.pages.dev/zh/docs/api/routing#路径参数

路由的匹配方式非常多,设置可以根据 header 参数进行匹配:https://honodev.pages.dev/zh/docs/api/routing#基于-host-头的路由

js
app.get("/about/me", async (c) => {
  const pathname = c.req.path; // `/about/me`

  const url = c.req.url; // `http://localhost:8787/about/me`

  const method = c.req.method; // `GET`
});
js
// 获取
c.req.header("User-Agent");
c.req.header(); // 返回是小写的!!!

// 设置
c.header("X-Message", "Hi!");

解析请求体

parseBody() 可以解析 multipart/form-data 或 application/x-www-form-urlencoded

https://honodev.pages.dev/zh/docs/api/request#parsebody

formData

js
const body = await c.req.formData();

multipart/form-data

js
const body = await c.req.parseBody();

application/json

js
await c.req.json();

text/plain

js
await c.req.text();

ArrayBuffer

js
await c.req.arrayBuffer();

blob

js
await c.req.blob();