NextResponse 没有向前端返回数据?

问题描述 投票:0回答:1

该API计算BMI并将其发送到前端。我已尝试控制台记录响应,但其中没有 BMI。我认为这是由于一些不同步行为造成的。

这是我的API代码

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

这是前端代码

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

我无法在控制台日志中看到 BMI,只能看到状态等标准响应。我如何在前端获取 BMI?

next.js nextjs-api-router
1个回答
0
投票

试试这个

const resp = await fetch(`/api/bmi?${queryParams}`, {

方法:“获取”, 标题:{ “内容类型”:“应用程序/json”, }, }).then(res => res.json());

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

© www.soinside.com 2019 - 2024. All rights reserved.