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



我的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({}),根据实际接口要求填写内容)。
- 检查Postman中是否存在
未处理非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
相关产品推荐
相关产品推荐

