Hono
https://pbs.twimg.com/media/GLtiVmZbYAABMax.png
$ npm create hono@latest
回傳Response的單元為「Handler」
「Middleware」會在Handler的之前與之後執行,處理Request與Response
Request->MA->MB->MC->Handler->MC->MB->MA->Response,如同洋蔥一般
建立Hono元件的函式
例如可用於建立一Middleware、Handler,或是再建立一個Hono
middleware、handler:是否回傳Response object
v2
範例
最小規模的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)
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);
});
資訊安全
在伺服器端使用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
實作