"How can I resolve an issue when accessing 'request.body' in an async function, which returns a 'ReadableStream' object instead of the expected data?"

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

"How can I resolve an issue when accessing 'request.body' in an async function, which returns a 'ReadableStream' object instead of the expected data?"

问题

当我在Nextjs13、typescript和prisma中创建我的CRUD时,GET方法处理程序正常工作,但PUT方法给我一些错误,我想知道我做错了什么。

当我获取请求时,它对我说:
这是请求正文:
ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

这是我的代码示例:

export async function PUT(request: NextApiRequest) {
    const id = "1";
    console.log("aqui esta")
    console.log(request)
    const { name, description, price, image, category, tags, link, variantType, sizes, allOfSizes, status, rating, numberOfReviews } = await request.body;
  
    console.log("Here is the request body:");
    console.log(request.body);
    console.log("Here is the name and description:");
    console.log(name, description);
  
    if (!id) {
      return new NextResponse(JSON.stringify({ error: "Product ID is required" }), {
        status: 400,
        headers: {
          "Content-Type": "application/json",
        },
      });
    }
  
    try {
      const existingProduct = await prisma.product.findUnique({
        where: {
          id: String(id),
        },
      });
  
      if (!existingProduct) {
        console.log("Product not found");
        return new NextResponse(JSON.stringify({ error: "Product not found" }), {
          status: 404,
          headers: {
            "Content-Type": "application/json",
          },
        });
      }
  
      const updatedProduct = await prisma.product.update({
        where: {
          id: String(id),
        },
        data: {
          name,
          description,
          price,
          image,
          category,
          tags: { set: tags || [] },
          link,
          variantType,
          sizes: { set: sizes || [] },
          allOfSizes: { set: allOfSizes || [] },
          status,
          rating,
          numberOfReviews,
        },
      });
  
      console.log("Product updated");
      return new NextResponse(JSON.stringify(updatedProduct), {
        status: 200,
        headers: {
          "Content-Type": "application/json",
        },
      });
    } catch (error) {
      console.error("Error updating product:", error);
      return new NextResponse(JSON.stringify({ error: "Internal Server Error" }), {
        status: 500,
        headers: {
          "Content-Type": "application/json",
        },
      });
    }
}

我的调试控制台输出:

compiling /api/products/[id]/route (client and server)...
- event compiled client and server successfully in 626 ms (371 modules)
aqui esta el request ndoikoi
NextRequest [Request] {
[Symbol(realm)]: {
settingsObject: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] }
},
[Symbol(state)]: {
method: 'PUT',
localURLsOnly: false,
unsafeRequest: false,
body: { stream: undefined, source: null, length: null },
client: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] },
reservedClient: null,
replacesClientId: '',
window: 'client',
keepalive: false,
serviceWorkers: 'all',
initiator: '',
destination: '',
priority: null,
origin: 'client',
policyContainer: 'client',
referrer: 'client',
referrerPolicy: '',
mode: 'cors',
useCORSPreflightFlag: true,
credentials: 'same-origin',
useCredentials: false,
cache: 'default',
redirect: 'follow',
integrity: '',
cryptoGraphicsNonceMetadata: '',
parserMetadata: '',
reloadNavigation: false,
historyNavigation: false,
userActivation: false,
taintedOrigin: false,
redirectCount: 0,
responseTainting: 'basic',
preventNoCacheCacheControlHeaderModification: false,
done: false,
timingAllowFailed: false,
headersList: HeadersList {
cookies: null,
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: [Array]
},
urlList: [ URL {} ],
url: URL {
href: 'http://localhost:3000/api/products/1',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/api/products/1',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
},
[Symbol(signal)]: AbortSignal { aborted: false },
[Symbol(headers)]: HeadersList {
cookies: null,
[Symbol(headers map)]: Map(15) {
'accept' => [Object],
'cache-control' => [Object],
'connection' => [Object],
'content-type' => [Object],
'host' => [Object],
'postman-token' => [Object],
'transfer-encoding' => [Object],
'user-agent' => [Object],
'x-forwarded-for' => [Object],
'x-forwarded-host' => [Object],
'x-forwarded-port' => [Object],
'x-forwarded-proto' => [Object],
'x-invoke-path' => [Object],
'x-invoke-query' => [Object],
'x-middleware-invoke' => [Object]
},
[Symbol(headers map sorted)]: [
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array]
]
},
[Symbol(internal request)]: {
cookies: RequestCookies { _parsed: Map(0) {}, _headers: [HeadersList] },
geo: {},
ip: undefined,
nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
url: 'http://localhost:3000/api/products/1'
}
}
Here is the request body:
ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
Here is the name and description:
undefined undefined
antesd de actualizar el supuestamente
{
id: '1',
name: 'prodcut name,
description: 'descripcion',
price: 200,
image: 'https://i.ibb.co/pr9WFLs/36.jpg',
category: 'C',
tags: [],
link: 'https://i.ibb.co/pr9WFLs/36.jpg',
variantType: 'a',
sizes: [],
allOfSizes: [],
status: 'sold',
rating: '4.5',
numberOfReviews: 150
}

当我尝试记录我的请求时,它显示:

Here is the request body:
ReadableStream { locked:
<details>
<summary>英文:</summary>
When i create my CRUD in Nextjs13, typescript, and prisma
the GET method handler works correctly, but the PUT give me some errors and i want to know what i doing wrong
when y get the request its says to me:
Here is the request body:
ReadableStream { locked: false, state: &#39;readable&#39;, supportsBYOB: false }
here my code example:
export async function PUT(request: NextApiRequest) {
const id = &quot;1&quot;;
console.log(&quot;aqui esta&quot;)
console.log(request)
const { name, description, price, image, category, tags, link, variantType, sizes, allOfSizes, status, rating, numberOfReviews } = await request.body;
console.log(&quot;Here is the request body:&quot;);
console.log(request.body);
console.log(&quot;Here is the name and description:&quot;);
console.log(name, description);
if (!id) {
return new NextResponse(JSON.stringify({ error: &quot;Product ID is required&quot; }), {
status: 400,
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
},
});
}
try {
const existingProduct = await prisma.product.findUnique({
where: {
id: String(id),
},
});
if (!existingProduct) {
console.log(&quot;Product not found&quot;);
return new NextResponse(JSON.stringify({ error: &quot;Product not found&quot; }), {
status: 404,
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
},
});
}
const updatedProduct = await prisma.product.update({
where: {
id: String(id),
},
data: {
name,
description,
price,
image,
category,
tags: { set: tags || [] },
link,
variantType,
sizes: { set: sizes || [] },
allOfSizes: { set: allOfSizes || [] },
status,
rating,
numberOfReviews,
},
});
console.log(&quot;Product updated&quot;);
return new NextResponse(JSON.stringify(updatedProduct), {
status: 200,
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
},
});
} catch (error) {
console.error(&quot;Error updating product:&quot;, error);
return new NextResponse(JSON.stringify({ error: &quot;Internal Server Error&quot; }), {
status: 500,
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
},
});
}}
the console output from my debugging:
compiling /api/products/[id]/route (client and server)...
- event compiled client and server successfully in 626 ms (371 modules)
aqui esta el request ndoikoi
NextRequest [Request] {
[Symbol(realm)]: {
settingsObject: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] }
},
[Symbol(state)]: {
method: &#39;PUT&#39;,
localURLsOnly: false,
unsafeRequest: false,
body: { stream: undefined, source: null, length: null },
client: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] },
reservedClient: null,
replacesClientId: &#39;&#39;,
window: &#39;client&#39;,
keepalive: false,
serviceWorkers: &#39;all&#39;,
initiator: &#39;&#39;,
destination: &#39;&#39;,
priority: null,
origin: &#39;client&#39;,
policyContainer: &#39;client&#39;,
referrer: &#39;client&#39;,
referrerPolicy: &#39;&#39;,
mode: &#39;cors&#39;,
useCORSPreflightFlag: true,
credentials: &#39;same-origin&#39;,
useCredentials: false,
cache: &#39;default&#39;,
redirect: &#39;follow&#39;,
integrity: &#39;&#39;,
cryptoGraphicsNonceMetadata: &#39;&#39;,
parserMetadata: &#39;&#39;,
reloadNavigation: false,
historyNavigation: false,
userActivation: false,
taintedOrigin: false,
redirectCount: 0,
responseTainting: &#39;basic&#39;,
preventNoCacheCacheControlHeaderModification: false,
done: false,
timingAllowFailed: false,
headersList: HeadersList {
cookies: null,
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: [Array]
},
urlList: [ URL {} ],
url: URL {
href: &#39;http://localhost:3000/api/products/1&#39;,
origin: &#39;http://localhost:3000&#39;,
protocol: &#39;http:&#39;,
username: &#39;&#39;,
password: &#39;&#39;,
host: &#39;localhost:3000&#39;,
hostname: &#39;localhost&#39;,
port: &#39;3000&#39;,
pathname: &#39;/api/products/1&#39;,
search: &#39;&#39;,
searchParams: URLSearchParams {},
hash: &#39;&#39;
}
},
[Symbol(signal)]: AbortSignal { aborted: false },
[Symbol(headers)]: HeadersList {
cookies: null,
[Symbol(headers map)]: Map(15) {
&#39;accept&#39; =&gt; [Object],
&#39;cache-control&#39; =&gt; [Object],
&#39;connection&#39; =&gt; [Object],
&#39;content-type&#39; =&gt; [Object],
&#39;host&#39; =&gt; [Object],
&#39;postman-token&#39; =&gt; [Object],
&#39;transfer-encoding&#39; =&gt; [Object],
&#39;user-agent&#39; =&gt; [Object],
&#39;x-forwarded-for&#39; =&gt; [Object],
&#39;x-forwarded-host&#39; =&gt; [Object],
&#39;x-forwarded-port&#39; =&gt; [Object],
&#39;x-forwarded-proto&#39; =&gt; [Object],
&#39;x-invoke-path&#39; =&gt; [Object],
&#39;x-invoke-query&#39; =&gt; [Object],
&#39;x-middleware-invoke&#39; =&gt; [Object]
},
[Symbol(headers map sorted)]: [
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array]
]
},
[Symbol(internal request)]: {
cookies: RequestCookies { _parsed: Map(0) {}, _headers: [HeadersList] },
geo: {},
ip: undefined,
nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
url: &#39;http://localhost:3000/api/products/1&#39;
}
}
Here is the request body:
ReadableStream { locked: false, state: &#39;readable&#39;, supportsBYOB: false }
Here is the name and description:
undefined undefined
antesd de actualizar el supuestamente
{
id: &#39;1&#39;,
name: &#39;prodcut name,
description: &#39;descripcion&#39;,
price: 200,
image: &#39;https://i.ibb.co/pr9WFLs/36.jpg&#39;,
category: &#39;C&#39;,
tags: [],
link: &#39;https://i.ibb.co/pr9WFLs/36.jpg&#39;,
variantType: &#39;a&#39;,
sizes: [],
allOfSizes: [],
status: &#39;sold&#39;,
rating: &#39;4.5&#39;,
numberOfReviews: 150}
here when i try to log my request:
Here is the request body:
ReadableStream { locked: false, state: &#39;readable&#39;, supportsBYOB: false }
how can i solve this?
</details>
# 答案1
**得分**: 1
我今天处理了这个错误,解决方法是在使用请求对象之前对其进行处理。所以,不要使用以下方式:
```javascript
const { name, description, price, image, category, tags, link, variantType, sizes, allOfSizes, status, rating, numberOfReviews } = await request.body;

而是使用以下方式:

const { name, description, price, image, category, tags, link, variantType, sizes, allOfSizes, status, rating, numberOfReviews } = await request.json();

这在这里有文档记录。

这只对可以在请求中接收到主体的POST、PUT和PATCH方法有效,如果您尝试在DELETE事务中使用它,将会收到相同的错误。

英文:

I was dealing with this error today and the solution was to treat the request object before you use it. So, instead of:

const { name, description, price, image, category, tags, link, variantType, sizes, allOfSizes, status, rating, numberOfReviews } = await request.body;

try:

const { name, description, price, image, category, tags, link, variantType, sizes, allOfSizes, status, rating, numberOfReviews } = await request.json();

This is documented here.

This will only work on POST, PUT and PATCH methods that can receive a body on the request, if you trying to this in a DELETE transaction you will get the same error.

huangapple
  • 本文由 发表于 2023年5月29日 04:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353421.html
匿名

发表评论

匿名网友

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

确定