CORS 中介軟體
Cloudflare Workers 有許多作為 Web API 的用例,並從外部前端應用程式呼叫它們。對於這些情況,我們必須實作 CORS,讓我們也使用中介軟體來完成此操作。
導入
ts
import { Hono } from 'hono'
import { cors } from 'hono/cors'
用法
ts
const app = new Hono()
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'
},
})
)
選項
選用 origin: string
| string[]
| (origin:string, c:Context) => string
「Access-Control-Allow-Origin」CORS 標頭的值。您也可以傳遞回呼函式,例如 origin: (origin) => (origin.endsWith('.example.com') ? origin : 'http://example.com')
。預設值為 *
。
選用 allowMethods: string[]
「Access-Control-Allow-Methods」CORS 標頭的值。預設值為 ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']
。
選用 allowHeaders: string[]
「Access-Control-Allow-Headers」CORS 標頭的值。預設值為 []
。
選用 maxAge: number
「Access-Control-Max-Age」CORS 標頭的值。
選用 credentials: boolean
「Access-Control-Allow-Credentials」CORS 標頭的值。
選用 exposeHeaders: string[]
「Access-Control-Expose-Headers」CORS 標頭的值。預設值為 []
。
環境相關的 CORS 設定
如果您想根據執行環境(例如開發或生產)調整 CORS 設定,從環境變數注入值是很方便的,因為這樣就不需要應用程式知道自身的執行環境。請參閱下面的範例以了解詳細資訊。
ts
app.use('*', async (c, next) => {
const corsMiddlewareHandler = cors({
origin: c.env.CORS_ORIGIN,
})
return corsMiddlewareHandler(c, next)
})