Harsh Singh
Harsh Singh

Reputation: 1

NextResponse not returning data to the frontend?

This API calculates the BMI and sends it to the frontend. I have tried console logging the response, but it does not have the BMI in it. I assume this is because of some unsynchronous behaviour.

This is my API code

import { NextRequest, NextResponse } from "next/server";
export async function GET(req,res) {
console.log('here');
const searchParams = await req.nextUrl.searchParams
console.log(searchParams);
const inc = await searchParams.get('inc')
const queryft =await searchParams.get('ft')
const queryhtInInc = await searchParams.get('htInInc')
const querywt = await searchParams.get('wt')
const queryhtInCm = await searchParams.get('htInCm')
let m;
let kg;
if (inc=="true") {
m = (parseInt(queryft, 10) * 12 + parseInt(queryhtInInc, 10)) * 0.0254;
kg = parseInt(querywt) * 0.45359237;
  } else {
m = parseFloat(queryhtInCm) * 0.01;
kg = parseInt(querywt);
  }

const bmi = parseFloat(kg) / (m * m);
console.log(bmi,"newbmi");
return NextResponse.json({bmi:bmi});
}

This is the frontend code

try {
const resp = await fetch(`/api/bmi?${queryParams}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
console.log(resp);
//   console.log(data1+"here");
// ... rest of your code
  } catch (error) {
console.error("API call failed:", error);
  }

I am unable to see the BMI in the console log, just the standard response like status etc. How can I obtain the BMI in my frontend?

Upvotes: 0

Views: 331

Answers (2)

Jack McBride
Jack McBride

Reputation: 86

Try this

const resp = await fetch(`/api/bmi?${queryParams}`, {method: "GET",
  headers: {
    "Content-Type": "application/json",
  },
}).then(res => res.json());

https://developer.mozilla.org/en-US/docs/Web/API/Response/json

Upvotes: 0

Dario K
Dario K

Reputation: 336

You need to parse the json from the response. There are a couple of ways you can do it but two main ones I use are:

Method 1: Asnyc/Await

const resp = await fetch(`/api/bmi?${queryParams}`, {
    method: "GET",
    headers: {
        "Content-Type": "application/json",
    },
});

const data = await resp.json()

console.log(data)

Method 2: .then.catch.finally

fetch(`/api/bmi?${queryParams}`, {
    method: "GET",
    headers: {
        "Content-Type": "application/json",
    },
})
    .then(res => {
        const data = await resp.json()

        console.log(data)
    })
    .catch(err => {
        // catch error here
    })
    .finally(() => {
        // Set loading to false if you have it
    })

You can even write a utility function to handle response from the server, something like this:

const handleAPIResponse = async (res: Response) => {
    if (!res.ok) {
        const errorText = await res.text()

        throw new Error(errorText || "Server error, please try again!")
    }

    return res.json()
}

Usage:

.then(handleAPIResponse)
.then(data => {
    console.log(data)
})

or

const res = await fetch(...)

const data = await handleAPIResponse(res)

Have a good day :)

Upvotes: 0

Related Questions