Skip to content

入门

🌐 Getting Started

使用 Hono 非常简单。我们可以设置项目、编写代码、使用本地服务器进行开发,并快速部署。相同的代码可以在任何运行时工作,只是入口点不同。让我们来看一下 Hono 的基本用法。

🌐 Using Hono is super easy. We can set up the project, write code, develop with a local server, and deploy quickly. The same code will work on any runtime, just with different entry points. Let's look at the basic usage of Hono.

入门

🌐 Starter

每个平台都提供了入门模板。使用以下 "create-hono" 命令。

🌐 Starter templates are available for each platform. Use the following "create-hono" command.

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono@latest my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono@latest my-app

然后系统会询问你想使用哪个模板。让我们以 Cloudflare Workers 为例进行选择。

🌐 Then you will be asked which template you would like to use. Let's select Cloudflare Workers for this example.

? Which template do you want to use?
    aws-lambda
    bun
    cloudflare-pages
❯   cloudflare-workers
    deno
    fastly
    nextjs
    nodejs
    vercel

模板将被拉入 my-app,所以请前往它并安装依赖。

🌐 The template will be pulled into my-app, so go to it and install the dependencies.

sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i

软件包安装完成后,运行以下命令启动本地服务器。

🌐 Once the package installation is complete, run the following command to start up a local server.

sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev

Hello World

你可以使用 Cloudflare Workers 开发工具“Wrangler”、Deno、Bun 或其他工具编写 TypeScript 代码,而无需意识到进行转译。

🌐 You can write code in TypeScript with the Cloudflare Workers development tool "Wrangler", Deno, Bun, or others without being aware of transpiling.

src/index.ts 中用 Hono 编写你的第一个应用。下面的示例是一个入门的 Hono 应用。

🌐 Write your first application with Hono in src/index.ts. The example below is a starter Hono application.

import 和最终的 export default 部分可能因运行时而异,但所有应用代码在任何地方都会运行相同的代码。

🌐 The import and the final export default parts may vary from runtime to runtime, but all of the application code will run the same code everywhere.

ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

export default app

启动开发服务器,并使用浏览器访问 http://localhost:8787

🌐 Start the development server and access http://localhost:8787 with your browser.

sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev

返回 JSON

🌐 Return JSON

返回 JSON 也很容易。以下是处理对 /api/hello 的 GET 请求并返回 application/json 响应的示例。

🌐 Returning JSON is also easy. The following is an example of handling a GET Request to /api/hello and returning an application/json Response.

ts
app.get('/api/hello', (c) => {
  return c.json({
    ok: true,
    message: 'Hello Hono!',
  })
})

请求和响应

🌐 Request and Response

获取路径参数、URL 查询值并附加响应标头的写法如下。

🌐 Getting a path parameter, URL query value, and appending a Response header is written as follows.

ts
app.get('/posts/:id', (c) => {
  const page = c.req.query('page')
  const id = c.req.param('id')
  c.header('X-Message', 'Hi!')
  return c.text(`You want to see ${page} of ${id}`)
})

我们可以轻松处理 POST、PUT 和 DELETE,而不仅仅是 GET。

🌐 We can easily handle POST, PUT, and DELETE not only GET.

ts
app.post('/posts', (c) => c.text('Created!', 201))
app.delete('/posts/:id', (c) =>
  c.text(`${c.req.param('id')} is deleted!`)
)

返回 HTML

🌐 Return HTML

你可以使用 the html HelperJSX 语法来编写 HTML。如果你想使用 JSX,请将文件重命名为 src/index.tsx 并进行配置(每个运行时不同,请检查)。下面是一个使用 JSX 的示例。

🌐 You can write HTML with the html Helper or using JSX syntax. If you want to use JSX, rename the file to src/index.tsx and configure it (check with each runtime as it is different). Below is an example using JSX.

tsx
const View = () => {
  return (
    <html>
      <body>
        <h1>Hello Hono!</h1>
      </body>
    </html>
  )
}

app.get('/page', (c) => {
  return c.html(<View />)
})

返回原始响应

🌐 Return raw Response

你也可以返回原始的 Response

🌐 You can also return the raw Response.

ts
app.get('/', () => {
  return new Response('Good morning!')
})

使用中间件

🌐 Using Middleware

中间件可以为你完成繁重的工作。例如,添加基本身份验证。

🌐 Middleware can do the hard work for you. For example, add in Basic Authentication.

ts
import { basicAuth } from 'hono/basic-auth'

// ...

app.use(
  '/admin/*',
  basicAuth({
    username: 'admin',
    password: 'secret',
  })
)

app.get('/admin', (c) => {
  return c.text('You are authorized!')
})

有一些有用的内置中间件,包括使用 JWT 的 Bearer 和认证、CORS 和 ETag。Hono 也提供使用外部库的第三方中间件,例如 GraphQL Server 和 Firebase Auth。同时,你也可以创建自己的中间件。

🌐 There are useful built-in middleware including Bearer and authentication using JWT, CORS and ETag. Hono also provides third-party middleware using external libraries such as GraphQL Server and Firebase Auth. And, you can make your own middleware.

适配器

🌐 Adapter

有用于平台依赖功能的适配器,例如,处理静态文件或 WebSocket。例如,要在 Cloudflare Workers 中处理 WebSocket,请导入 hono/cloudflare-workers

🌐 There are Adapters for platform-dependent functions, e.g., handling static files or WebSocket. For example, to handle WebSocket in Cloudflare Workers, import hono/cloudflare-workers.

ts
import { upgradeWebSocket } from 'hono/cloudflare-workers'

app.get(
  '/ws',
  upgradeWebSocket((c) => {
    // ...
  })
)

下一步

🌐 Next step

大多数代码可以在任何平台上运行,但每个平台都有相应的指南。例如,如何设置项目或如何部署。请查看你要使用的具体平台页面,以创建你的应用!

🌐 Most code will work on any platform, but there are guides for each. For instance, how to set up projects or how to deploy. Please see the page for the exact platform you want to use to create your application!

Hono 中文网 - 粤ICP备13048890号