Skip to content

Azure 函数

🌐 Azure Functions

Azure Functions 是微软 Azure 的一个无服务器平台。你可以在响应事件时运行你的代码,它会自动为你管理底层计算资源。

Hono 最初并不是为 Azure Functions 设计的,但通过 Azure Functions Adapter,它也可以在其上运行。

🌐 Hono was not designed for Azure Functions at first, but with Azure Functions Adapter, it can run on it as well.

它适用于在 Node.js 18 或更高版本上运行的 Azure Functions V4

🌐 It works with Azure Functions V4 running on Node.js 18 or above.

1. 安装 CLI

🌐 1. Install CLI

要创建一个 Azure Function,你必须先安装 Azure Functions Core Tools

🌐 To create an Azure Function, you must first install Azure Functions Core Tools.

在 macOS 上

🌐 On macOS

sh
brew tap azure/functions
brew install azure-functions-core-tools@4

其他操作系统请点击此链接:

🌐 Follow this link for other OS:

2. 设置

🌐 2. Setup

在当前文件夹中创建一个 TypeScript Node.js V4 项目。

🌐 Create a TypeScript Node.js V4 project in the current folder.

sh
func init --typescript

更改主机的默认路由前缀。在 host.json 的根 JSON 对象中添加此属性:

🌐 Change the default route prefix of the host. Add this property to the root json object of host.json:

json
"extensions": {
    "http": {
        "routePrefix": ""
    }
}

INFO

默认的 Azure Functions 路由前缀是 /api。如果你没有按照上述方式更改它,请确保所有 Hono 路由都以 /api 开头。

现在你已准备好安装 Hono 和 Azure Functions Adapter:

🌐 Now you are ready to install Hono and the Azure Functions Adapter with:

sh
npm i @marplex/hono-azurefunc-adapter hono
sh
yarn add @marplex/hono-azurefunc-adapter hono
sh
pnpm add @marplex/hono-azurefunc-adapter hono
sh
bun add @marplex/hono-azurefunc-adapter hono

3. 你好,世界

🌐 3. Hello World

创建 src/app.ts

🌐 Create src/app.ts:

ts
// src/app.ts
import { Hono } from 'hono'
const app = new Hono()

app.get('/', (c) => c.text('Hello Azure Functions!'))

export default app

创建 src/functions/httpTrigger.ts

🌐 Create src/functions/httpTrigger.ts:

ts
// src/functions/httpTrigger.ts
import { app } from '@azure/functions'
import { azureHonoHandler } from '@marplex/hono-azurefunc-adapter'
import honoApp from '../app'

app.http('httpTrigger', {
  methods: [
    //Add all your supported HTTP methods here
    'GET',
    'POST',
    'DELETE',
    'PUT',
  ],
  authLevel: 'anonymous',
  route: '{*proxy}',
  handler: azureHonoHandler(honoApp.fetch),
})

4. 跑

🌐 4. Run

在本地运行开发服务器。然后,在你的网页浏览器中访问 http://localhost:7071

🌐 Run the development server locally. Then, access http://localhost:7071 in your Web browser.

sh
npm run start
sh
yarn start
sh
pnpm start
sh
bun run start

5. 部署

🌐 5. Deploy

INFO

在你可以部署到 Azure 之前,你需要在云基础设施中创建一些资源。请访问微软文档:为你的函数创建支持的 Azure 资源

构建项目以进行部署:

🌐 Build the project for deployment:

sh
npm run build
sh
yarn build
sh
pnpm build
sh
bun run build

将你的项目部署到 Azure 云中的函数应用。将 <YourFunctionAppName> 替换为你的应用名称。

🌐 Deploy your project to the function app in Azure Cloud. Replace <YourFunctionAppName> with the name of your app.

sh
func azure functionapp publish <YourFunctionAppName>

Hono 中文网 - 粤ICP备13048890号