You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS应用调用API返回null,求排查代码问题

NextJS API调用返回null,代码存在哪些问题?

我在Postman中测试了目标API调用(测试截图如下),现在用NextJS编写应用实现相同逻辑,但控制台输出的data为null,请帮忙排查代码中缺失的部分。

Postman测试截图1
Postman测试截图2
Postman测试截图3

我的NextJS代码:

import Head from 'next/head'
import Header from '@components/Header'
import Footer from '@components/Footer'

export default function Home({ data }) {
  console.log(data);
  return (
    <div>
      <h1>ExtBot Logs</h1>
    </div>
  )
}

export async function getServerSideProps() {
  const username = 'user';
  const password = 'password';

  try {
    const response = await fetch(
      'my_url',
      {
        method: 'POST',
        headers: {
          'Authorization': 'Basic ' + base64.encode(username + ":" + password),
          'URL': 'askhelp',
          'Content-Type': 'application/json',
        },
      }
    );
    
    if (!response.ok) {
      throw new Error('Request failed with status ' + response.status);
    }
    
    const data = await response.json();
    console.log('API response:', response); // Log the entire response object
    console.log('API data:', data); // Log the extracted data
    return {
      props: {
        data: JSON.parse(JSON.stringify(data)),
        hello: "world",
      }
    };
  } catch (err) {
    console.log('API request error:', err);
    return {
      props: {
        data: null,
        hello: "world",
      }
    };
  }
}

代码中存在的问题及修复方案:

  • 缺失base64编码实现:代码中直接使用base64.encode,但NextJS的Node.js环境中没有全局的base64对象。替换为Node.js内置的Buffer处理:

    'Authorization': 'Basic ' + Buffer.from(username + ":" + password).toString('base64'),
    
  • 请求URL未替换为真实地址:代码中的'my_url'是占位符,需要替换为Postman中使用的真实API地址。

  • 请求头配置可能与Postman不符:

    • 检查Postman中是否存在URL: askhelp这个请求头,若不存在则删除该配置;若askhelp是API路径的一部分,应拼接到请求URL中(如'my_url/askhelp')。
    • 确认Postman是否发送了请求体:如果API需要JSON请求体,代码中缺少body参数,需添加(比如body: JSON.stringify({}),根据实际接口要求填写内容)。
  • 未处理非JSON响应场景:若API返回的不是JSON格式,response.json()会抛出错误进入catch块,导致data为null。可以先捕获该情况,查看返回内容:

    try {
      const data = await response.json();
      // ...后续逻辑
    } catch (parseErr) {
      const text = await response.text();
      console.log('API返回非JSON内容:', text);
      throw parseErr;
    }
    
  • 冗余的JSON序列化操作:JSON.parse(JSON.stringify(data))完全多余,直接返回data即可:

    props: {
      data,
      hello: "world",
    }
    

内容的提问来源于stack exchange,提问作者Mark Locklear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:44:57