Big*_*s01 6 javascript fetch-api next.js next.js13
我正在向服务器端代码发送一个无法正确读取的值。我正在使用 NextJS 实验 App 目录
//src/app/api/auth/route.js
export async function POST(req, res) {
console.log(req.body);
const { address } = req.body;
const isAuthenticated = await checkBalance(address, threshold);
if (isAuthenticated) {
return new Response("Authorized", { status: 200 });
} else if (isAuthenticated == false) {
return new Response("Unauthorized", { status: 401 });
} else if (isAuthenticated == undefined) {
return new Response("Error", { status: 500 });
}
}
Run Code Online (Sandbox Code Playgroud)
控制台日志是:ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
常量地址是undefined.
这是 API 调用:
const response = await fetch("/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ address: walletAddress }),
});
const data = await response.json();
Run Code Online (Sandbox Code Playgroud)
我在类似问题的另一个答案中读到 nextjs12+ 应该自动解析请求 - 我做错了什么?我假设 nextjs 有一个用于解码 ReadableStream 的协议,但我在文档或示例中找不到任何内容,也许是因为有一个与框架无关的方法来解码我未知的对象?
先感谢您。
小智 25
我也遇到过类似的问题,你可以试试这个:
const body = await req.json()
const {address} = body
// the rest of your code
Run Code Online (Sandbox Code Playgroud)
小智 7
您需要等待来自 nextjs 的请求才能获取 body 对象。就像下面的代码一样:
import { NextResponse } from "next/server";
export async function POST(req) {
const body = await req.json();
console.log(body);
return NextResponse.json(body);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10130 次 |
| 最近记录: |