reactjs - 如何在 Next.js 13.2 路由處理器中訪問請求主體
我正在嘗試向我的 API 發送一個 POST 請求。然而,嘗試在路由處理程式中訪問請求正文會導致以下錯誤:
代碼:
export async function POST(request: Request) {
const postBody: postProps = JSON.parse(request.body) // 👈 Error here on request.body
...
}錯誤:類型 'ReadableStream' 的參數無法分配給類型 'string' 的參數。
任何幫助都將不勝感激
答案#1
你需要在 Request 物件上呼叫 json()。
export async function POST(request: Request) {
const res = await request.json() // res now contains body
}
答案#2
我在使用 App Router 的 Next.js 中,驗證 Clerk 的 webhook 時遇到了問題。
以下對我有效。
import { Webhook } from "svix";
export async function POST(req: NextRequest) {
const svix_id = req.headers.get("svix-id") ?? '';
const svix_timestamp = req.headers.get("svix-timestamp") ?? '';
const svix_signature = req.headers.get("svix-signature") ?? '';
const body = await req.text(); // This get's the raw body as a string
const sivx = new Webhook("your_secret_key_here")
const payload = sivx.verify(body, {
"svix-id": svix_id,
"svix-timestamp": svix_timestamp,
"svix-signature": svix_signature,
});
// The payload is the json.
console.log(payload);
// The rest of your code
return NextResponse.json(null, { status: 200 })
}
參考:
https://developer.mozilla.org/zh-TW/docs/Web/API/Response/text
