英文:
"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: 'readable', supportsBYOB: false }
here my code example:
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",
},
});
}}
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: '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 when i try to log my request:
Here is the request body:
ReadableStream { locked: false, state: 'readable', 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论