CORS 中间件
将 Cloudflare Workers 用作 Web API,并由外部前端应用调用,是一种常见场景。 这些场景需要实现 CORS,也可以通过中间件完成。
导入
ts
import { Hono } from 'hono'
import { cors } from 'hono/cors'用法
ts
const app = new Hono()
// CORS should be called before the route
app.use('/api/*', cors())
app.use(
'/api2/*',
cors({
origin: 'http://example.com',
allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
allowMethods: ['POST', 'GET', 'OPTIONS'],
exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
maxAge: 600,
credentials: true,
})
)
app.all('/api/abc', (c) => {
return c.json({ success: true })
})
app.all('/api2/abc', (c) => {
return c.json({ success: true })
})多个源:
ts
app.use(
'/api3/*',
cors({
origin: ['https://example.com', 'https://example.org'],
})
)
// Or you can use "function"
app.use(
'/api4/*',
cors({
// `c` is a `Context` object
origin: (origin, c) => {
return origin.endsWith('.example.com')
? origin
: 'http://example.com'
},
})
)根据源动态决定允许的方法:
ts
app.use(
'/api5/*',
cors({
origin: (origin) =>
origin === 'https://example.com' ? origin : '*',
// `c` is a `Context` object
allowMethods: (origin, c) =>
origin === 'https://example.com'
? ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE']
: ['GET', 'HEAD'],
})
)选项
optional origin: string | string[] | (origin:string, c:Context) => string
CORS 响应头“Access-Control-Allow-Origin”的值。也可以传入回调函数,如 origin: (origin) => (origin.endsWith('.example.com') ? origin : 'http://example.com')。默认值为 *。
optional allowMethods: string[] | (origin:string, c:Context) => string[]
CORS 响应头“Access-Control-Allow-Methods”的值。也可以传入回调函数,根据源动态决定允许的方法。默认值为 ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']。
optional allowHeaders: string[]
CORS 响应头“Access-Control-Allow-Headers”的值。默认值为 []。
optional maxAge: number
CORS 响应头“Access-Control-Max-Age”的值。
optional credentials: boolean
CORS 响应头“Access-Control-Allow-Credentials”的值。
optional exposeHeaders: string[]
CORS 响应头“Access-Control-Expose-Headers”的值。默认值为 []。
根据环境配置 CORS
如果要根据开发或生产等执行环境调整 CORS 配置,通过环境变量注入值会很方便,因为这样应用无需感知自身的执行环境。以下示例展示了这种方式。
ts
app.use('*', async (c, next) => {
const corsMiddlewareHandler = cors({
origin: c.env.CORS_ORIGIN,
})
return corsMiddlewareHandler(c, next)
})与 Vite 配合使用
将 Hono 与 Vite 配合使用时,应在 vite.config.ts 中将 server.cors 设为 false,关闭 Vite 内置的 CORS 功能,以防与 Hono 的 CORS 中间件冲突。
ts
// vite.config.ts
import { cloudflare } from '@cloudflare/vite-plugin'
import { defineConfig } from 'vite'
export default defineConfig({
server: {
cors: false, // disable Vite's built-in CORS setting
},
plugins: [cloudflare()],
})