#Error when access json of NextRequest

1 messages · Page 1 of 1 (latest)

olive ermine
#

this is my code = ```import { NextRequest, NextResponse } from "next/server";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";

export default async function POST(req: NextRequest) {
try {
console.log("Inside registerAdmin route");
const reqBody = await req.json();
const { accountAddress, emailId, password } = reqBody;
console.log(reqBody: ${JSON.stringify(reqBody)});
console.log(accountAddress: ${accountAddress});
console.log("Reading the contract");
const registerAdmin = useScaffoldContractWrite({
contractName: "YourContract",
functionName: "registerAdmin",
args: [emailId, password, accountAddress],
});
console.log("await registerAdmin.writeAsync()");
await registerAdmin.writeAsync();
return NextResponse.json({
message: "Admin registered successfully",
success: true,
});
} catch (err: any) {
// return the error message as a json object, and set the status code to 500
console.log(Error in signup route: ${err.message});
return NextResponse.json({ error: err.message }, { status: 500 });
}
}
whenever I try to register I get the error =Inside registerAdmin route
Error in signup route: req.json is not a function
error - TypeError: Response.json is not a function
at Function.json (/media/vivekup3424/New Volume/IIITM Gwalior/Sem 4/summer_project/Degchain-Frontend/packages/nextjs/node_modules/next/dist/server/web/spec-extension/response.js:61:35)
at POST (webpack-internal:///(api)/./pages/api/admin/register.ts:39:70)
at Object.apiResolver (/media/vivekup3424/New Volume/IIITM Gwalior/Sem 4/summer_project/Degchain-Frontend/packages/nextjs/node_modules/next/dist/server/api-utils/node.js:372:15)
at runMicrotasks (<anonymous>)this is my package.json ="mongodb": "^5.7.0",
"mongoose": "^7.3.4",
"next": "^13.1.6",
"nextjs-progressbar": "^0.0.16",
"react": "^18.2.0",
"react-blockies": "^1.4.1",```

royal heathBOT
#

Hi @olive ermine. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the error message you're receiving, it seems like the issue is with the req.json() and NextResponse.json() methods. In the Next.js documentation, it's mentioned that the req object in an API route handler is an instance of http.IncomingMessage, plus some additional functionality specific to Next.js. The req.json() method is not a built-in method of http.IncomingMessage and is not mentioned in the provided extracts.

For the NextResponse.json() method, it's used to produce a response with the given JSON body. However, the way you're using it in your code seems to be incorrect. According to the provided extracts, the correct usage should be NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }).

Here's how you should modify your code:

import { NextRequest, NextResponse } from "next/server";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";
#

export default async function POST(req: NextRequest) {
try {
console.log("Inside registerAdmin route");
const reqBody = await req.json();
const { accountAddress, emailId, password } = reqBody;
console.log(reqBody: ${JSON.stringify(reqBody)});
console.log(accountAddress: ${accountAddress});
console.log("Reading the contract");
const registerAdmin = useScaffoldContractWrite({
contractName: "YourContract",
functionName: "registerAdmin",
args: [emailId, password, accountAddress],
});
console.log("await registerAdmin.writeAsync()");
await registerAdmin.writeAsync();
return NextResponse.json({ message: "Admin registered successfully", success: true });
} catch (err: any) {
// return the error message as a json object, and set the status code to 500
console.log(Error in signup route: ${err.message});
return NextResponse.json({ error: err.message }, { status: 500 });
}
}


Please note that this is based on the information provided in the extracts. If the issue persists, I recommend checking the official Next.js documentation or the relevant package documentation for more details.
----------------------
`Note: you can ask me a follow up question by @ mentioning me again` :speech_balloon:
----------------------
#

@olive ermine kapa.ai is still learning and improving, please let us know how it did by reacting below

olive ermine
#

I am using axios for putting the request = console.log("Admin Signup"); response = await axios.post("/api/admin/register", { emailId, password, accountAddress }); is this causing some error

#

@royal heath I am using axios for putting the request =

console.log("Admin Signup");
response = await axios.post("/api/admin/register", { emailId, password, accountAddress });

is this causing some error

royal heathBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the provided extracts, there's no specific information about using Axios with Next.js. However, Axios is a widely used library for making HTTP requests and it should work fine with Next.js.

The code snippet you provided seems correct for making a POST request with Axios. If you're encountering an error, it could be due to a variety of reasons such as the endpoint /api/admin/register not being set up correctly, the server not being able to handle the request, or issues with the data you're sending.

If you're receiving an error, please provide the specific error message or describe the issue in more detail. This will help in providing a more accurate solution.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@olive ermine kapa.ai is still learning and improving, please let us know how it did by reacting below

olive ermine
#
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";

export default async function POST(req: NextRequest) {
  try {
    console.log("Inside registerAdmin route");
    const reqBody = await req.json();
    const { accountAddress, emailId, password } = reqBody;
    console.log(`reqBody: ${JSON.stringify(reqBody)}`);
    console.log(`accountAddress: ${accountAddress}`);
    console.log("Reading the contract");
    const registerAdmin = useScaffoldContractWrite({
      contractName: "YourContract",
      functionName: "registerAdmin",
      args: [emailId, password, accountAddress],
    });
    console.log("await registerAdmin.writeAsync()");
    await registerAdmin.writeAsync();
    return NextResponse.json({
      message: "Admin registered successfully",
      success: true,
    });
  } catch (err: any) {
    // return the error message as a json object, and set the status code to 500
    console.log(`Error in signup route: ${err.message}`);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
``` this is the endpoint and this is the error = ```Inside registerAdmin route
Error in signup route: req.json is not a function
error - TypeError: Response.json is not a function``` clearly first error is at ```const reqBody = await req.json();```
#

@royal heath this is the endpoint = ```import { NextRequest, NextResponse } from "next/server";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";

export default async function POST(req: NextRequest) {
try {
console.log("Inside registerAdmin route");
const reqBody = await req.json();
const { accountAddress, emailId, password } = reqBody;
console.log(reqBody: ${JSON.stringify(reqBody)});
console.log(accountAddress: ${accountAddress});
console.log("Reading the contract");
const registerAdmin = useScaffoldContractWrite({
contractName: "YourContract",
functionName: "registerAdmin",
args: [emailId, password, accountAddress],
});
console.log("await registerAdmin.writeAsync()");
await registerAdmin.writeAsync();
return NextResponse.json({
message: "Admin registered successfully",
success: true,
});
} catch (err: any) {
// return the error message as a json object, and set the status code to 500
console.log(Error in signup route: ${err.message});
return NextResponse.json({ error: err.message }, { status: 500 });
}
}

 and this is the error = 

Inside registerAdmin route
Error in signup route: req.json is not a function
error - TypeError: Response.json is not a function```

clearly first error is at

const reqBody = await req.json();

royal heathBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The error message you're seeing indicates that req.json() is not a function. This is because in Next.js, the req object in an API route handler is an instance of http.IncomingMessage, plus some additional functionality specific to Next.js. The req.json() method is not a built-in method of http.IncomingMessage and is not mentioned in the provided extracts.

However, in the provided extracts, there's an example of how to read the Request body using the standard Web API methods:

import { NextResponse } from 'next/server'
 
export async function POST(request: Request) {
 const res = await request.json()
 return NextResponse.json({ res })
}

(Source: Next.js Documentation (https://nextjs.org/docs/app/building-your-application/routing/route-handlers))

In this example, request.json() is used to read the request body. This suggests that req.json() should be a valid method. If it's not working, it could be due to a version mismatch or some other configuration issue.

As for the Response.json is not a function error, it's likely because NextResponse.json() is being used incorrectly in your code. According to the provided extracts, the correct usage should be NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }).

import { NextResponse } from 'next/server'
 
export async function GET(request: Request) {
 return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}

(Source: Next.js Documentation (https://nextjs.org/docs/app/api-reference/functions/next-response))

#

Please check your Next.js version and ensure it's compatible with the code you're writing. If the issue persists, I recommend checking the official Next.js documentation or the relevant package documentation for more details.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@olive ermine kapa.ai is still learning and improving, please let us know how it did by reacting below

olive ermine
#

@royal heath so what should be the correct code

royal heathBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the provided extracts, the correct way to handle a POST request and send a JSON response in Next.js would be:

import { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    console.log("Inside registerAdmin route");
    const reqBody = await req.json();
    const { accountAddress, emailId, password } = reqBody;
    console.log(`reqBody: ${JSON.stringify(reqBody)}`);
    console.log(`accountAddress: ${accountAddress}`);
    console.log("Reading the contract");
    const registerAdmin = useScaffoldContractWrite({
      contractName: "YourContract",
      functionName: "registerAdmin",
      args: [emailId, password, accountAddress],
    });
    console.log("await registerAdmin.writeAsync()");
    await registerAdmin.writeAsync();
    res.status(200).json({
      message: "Admin registered successfully",
      success: true,
    });
  } catch (err) {
    // return the error message as a json object, and set the status code to 500
    console.log(`Error in signup route: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
}

Please note that this is based on the information provided in the extracts. If the issue persists, I recommend checking the official Next.js documentation or the relevant package documentation for more details.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@olive ermine kapa.ai is still learning and improving, please let us know how it did by reacting below

olive ermine
#

@royal heath this is my nextjs version = "mongoose": "^7.3.4", "next": "^13.1.6", "nextjs-progressbar": "^0.0.16", "react": "^18.2.0", so the code which you have given above will work here?

royal heathBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, the code provided should work with your current Next.js version (13.1.6). The NextApiRequest and NextApiResponse types are part of Next.js and are used to type the request and response objects in API routes. The req.json() method is used to parse the incoming request body and the res.status().json() method is used to send a JSON response with a specific status code.

However, please note that the useScaffoldContractWrite function is not part of Next.js and its implementation is not provided in the extracts. Make sure that this function is correctly implemented in your application.

If you encounter any issues, I recommend checking the official Next.js documentation or the relevant package documentation for more details.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@olive ermine kapa.ai is still learning and improving, please let us know how it did by reacting below

olive ermine
#

@royal heath this is my code = ```import { NextRequest, NextResponse } from "next/server";
import { useScaffoldContractWrite } from "~~/hooks/scaffold-eth";

export default async function POST(req: NextRequest) {
try {
const reqBody = await req.json();
const { accountAddress, emailId, password } = reqBody;
console.log(reqBody: ${JSON.stringify(reqBody)});
console.log(accountAddress: ${accountAddress});
console.log("Reading the contract");
const registerAdmin = useScaffoldContractWrite({
contractName: "YourContract",
functionName: "registerAdmin",
args: [emailId, password, accountAddress],
});
console.log("await registerAdmin.writeAsync()");
await registerAdmin.writeAsync();
return NextResponse.json({
message: "Admin registered successfully",
success: true,
});
} catch (err: any) {
// return the error message as a json object, and set the status code to 500
console.log(Error in signup route: ${err.message});
return NextResponse.json({ error: err.message }, { status: 500 });
}
}
this is my package.json = "ipfs-http-client": "^60.0.1",
"jsonwebtoken": "^9.0.1",
"mongodb": "^5.7.0",
"mongoose": "^7.3.4",
"next": "^13.1.6",
"nextjs-progressbar": "^0.0.16",
"react": "^18.2.0",
"react-blockies": "^1.4.1",
"react-copy-to-clipboard": "^5.1.0",this is my nodejs version =16.20.2 is the nodejs version causing this error =req.json() is not a function```

royal heathBOT
#

Let me check the knowledge base for you. One moment! :books: