解码 ReadableStream 对象 nextjs 13 API 路由

huangapple go评论72阅读模式
英文:

Decode ReadableStream object nextjs 13 api route

问题

我正在向我的服务器端代码发送一个值,但它没有被正确读取。我正在使用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("已授权", { status: 200 });
  } else if (isAuthenticated == false) {
    return new Response("未经授权", { status: 401 });
  } else if (isAuthenticated == undefined) {
    return new Response("错误", { status: 500 });
  }
}

控制台日志显示为:ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

addressundefined

这是 API 调用代码:

const response = await fetch("/api/auth", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ address: walletAddress }),
});
const data = await response.json();

我在另一个类似问题的答案中读到,Next.js 12+ 应该自动解析请求-我做错了什么吗?我假设 Next.js 已经有一个协议来解码 ReadableStream,但我在文档或示例中找不到相关信息,也许是因为有一种跨框架的解码对象的方法我不熟悉?

提前感谢。

英文:

I'm sending a value to my server side code that isn't being read correctly. I'm using the NextJS experimental App directory

//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 });
  }
}

console log is: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

const address is undefined.

This is the api call:

const response = await fetch("/api/auth", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ address: walletAddress }),
        });
        const data = await response.json();

I read in another answer to a similar question that nextjs12+ is supposed to parse the request automatically- what am I doing wrong? I'm assuming that nextjs has a protocol in place for decoding the ReadableStream but I can't find anything in the docs or examples for this, maybe because there is a framework agnostic method for decoding the object that is unknown to me?

Thank you in advance.

答案1

得分: 19

这是您要翻译的内容:

"我遇到了类似的问题,你可以尝试这个:

const body = await req.json()
const {address} = body
// 剩下的代码
```"

<details>
<summary>英文:</summary>

I&#39;ve faced a similiar problem, you can try this:

    const body = await req.json()
    const {address} = body
    // the rest of your code 

</details>



# 答案2
**得分**: 6

你需要**等待**来自Next.js的请求,以便获取body对象。就像下面的代码一样:

```javascript
import { NextResponse } from "next/server";

export async function POST(req) {
    const body = await req.json();
    console.log(body);

    return NextResponse.json(body);
}
英文:

you need to await the request from nextjs in order to get the body object.
Like the code bellow:

import { NextResponse } from &quot;next/server&quot;;

export async function POST(req) {
	
	const body = await req.json();
	console.log(body);
	
	return NextResponse.json(body);
}

答案3

得分: 0

...
const { address } = req.body
const isAuthenticated = await checkBalance(address, threshold);
...
英文:

I think what you want to do is:

...
const { address } = req.body
const isAuthenticated = await checkBalance(address, threshold);
...

答案4

得分: 0

一位Discord用户推荐使用const address = await req.json();,而不是const {address} = req.body,它有效。

英文:

A discord user recommended const address = await req.json(); instead of const {address} = req.body and it works.

huangapple
  • 本文由 发表于 2023年3月31日 22:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定