Hono
https://pbs.twimg.com/media/GLtiVmZbYAABMax.png
建構專案
$ npm create hono@latest
middleware、handler:是否回傳Response object
v2
https://youtu.be/lgy0FKho2yI
範例
最小規模的SPA
手動
code:javascript
import { Hono } from 'hono'
import { toSSG } from 'hono/ssg'
import fs from 'fs/promises'
const app = new Hono()
app.get('/welcome', (c) => {
return c.render(
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
)
})
toSSG(app, fs)
Vite Plugin
hono/ssg
Plugin
code:js
toSSG(app, fs {
})
@hono/ssg-plugin/essential
Sitemap
robots.txt
RSS/Atom
code:javascript
app.get('/', (c) => {
return c.html(<h1>redirect to me</h1>);
});
app.get('*', (c) => {
const url = new URL(c.req.url);
const redirectUrl = url.pathname.substring(1) + url.search;
return c.redirect(redirectUrl, 302);
});
2025-02-21
1. 點擊登入按鍵
取得authorizationUri(例如Google的登入頁面),並跳至該頁面
2. 登入後,取得重新導向的網址,並跳至該頁面
在重新導向的payload內會包含登入的相關資料
3. 檢查相關資料是否已經存在
不存在時,自動註冊
存在時
1. 取得使用者資料
3. 加入至response header的set-cookie內,儲存於客戶端
往後可從使用者的cookie自動判斷是否已經登入
資訊安全
在伺服器端使用React
1. 讓Hono解釋JSX
更改副檔名為.tsx
編輯tsconfig.json
code:tsconfig.json(diff)
"compilerOptions": {
// ...
"jsx": "react-jsx",
- "jsxImportSource": "hono/jsx"
+ "jsxImportSource": "react"
},
2. 撰寫JSX
src/index.tsx
code:index.tsx
// ...
app.get('/', (c) => {
const Content = <h1>Hello</h1>
})
3. 算繪
src/index.tsx
code:index.tsx
// ...
import { renderToString } from 'react-dom/server'
app.get('/', (c) => {
const Content = <h1>Hello</h1>
return c.html(renderToString(Content))
})
renderToString
renderToStaticMarkup
renderToReadableStream
React的便利功能
Document Metadata
Resource Loading
Streaming + Suspense
React的生態系
在Hono上使用React
React Renderer Middleware
@hono/react-renderer
code:index.tsx
// ...
import { reactRenderer } from '@hono/react-renderer'
app.get(
'*',
reactRenderer(({ children }) => {
return (
<html>
<body>
<h1>React + Hono</h1>
<div>{children}</div>
</body>
</html>
)
})
)
app.get('/', (c) => {
return c.renderer(<p>Welcome!</p>)
})
vite-ssr-components
vite.config.ts
src/renderer.tsx
登場人物
1. Resource owner
2. Resource server
3. Client
4. 授權server
流程
四種准許類型
准許授權code
准許隱式
准許client憑證
准許resource owner密碼憑證
准許授權code
取得授權code
1. 開始OAuth
2. 認證使用者
3. 同意委託權限
取得access token
取得resource
實作