我正在向服务器端代码发送一个不能正确读取的值。我使用NextJS实验应用程序目录
//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 });
}
}
控制台日志为:ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
const address isundefined
.
这是api调用:
const response = await fetch("/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ address: walletAddress }),
});
const data = await response.json();
我在另一个类似的问题的答案中读到nextjs12+应该自动解析请求-我做错了什么?我假设nextjs有一个解码ReadableStream的协议,但我在文档或例子中找不到任何东西,也许是因为有一个框架不可知的方法来解码我未知的对象?
提前谢谢你。
我遇到过一个类似的问题,你可以试试这个:
const body = await req.json()
const {address} = body
// the rest of your code
你需要等待来自nextjs的请求,以便获得body对象。就像下面的代码:
import { NextResponse } from "next/server";
export async function POST(req) {
const body = await req.json();
console.log(body);
return NextResponse.json(body);
}
我想你应该这样做:
...
const { address } = req.body
const isAuthenticated = await checkBalance(address, threshold);
...
一个discord用户推荐const address = await req.json();
而不是const {address} = req.body
,并且它有效。