javascript - Next.JS:无法在 getInitialProps 中调用内部 API。出现错误:读取 ECONNRESET
问题描述
当我在 getInitialProps 中使用内部 API 路由时,我收到此错误。
Error: read ECONNRESET
at _errnoException (util.js:1003:13)
at TCP.onread (net.js:620:25)
static async getInitialProps({ reduxStore }) {
const res = await Axios.get("/api/recent/1");
await reduxStore.dispatch({ type: LIST, payload: res.data });
return { }
}
但如果我使用外部 API 服务器,它工作正常。
static async getInitialProps({ reduxStore }) {
const res = await Axios.get("http://abc.herokuapp.com/api/recent/1");
await reduxStore.dispatch({ type: LIST, payload: res.data });
return { }
}
如果我在 componentDidMount 中调用 API,它在这两种情况下都可以正常工作,但在 getinitialProps 中,我无法处理我的 Express 服务器上的内部 API。
请帮忙!我的代码有问题吗?我正在搜索过去几个小时,但无法解决。
解决方案
您可以baseUrl
从请求中提取。
async getInitialProps({ req }) {
const protocol = req.headers['x-forwarded-proto'] || 'http'
const baseUrl = req ? `${protocol}://${req.headers.host}` : ''
const res = await fetch(baseUrl + '/api/recent/1')
...
}
推荐阅读
- c# - 禁用 DropDownList 并能够将值传递给更新模型
- c++ - 从对向量中按值擦除元素
- android - Android Studio:如何在布局 xml 文件中自动添加结束/结束标记
- python - 将 Tenor 的索引和值组合成一个新的张量
- javascript - 父位置更改时JQuery删除元素
- ios - 如何使用 React-Native 在 iOS 中禁用屏幕截图
- excel - 基于 If Not VBA 是否可以删除范围而不是删除整行?
- php - 我的代码中是否有任何问题“电子邮件无法使用我的 G-suite 帐户电子邮件”与 phpmailer
- c++ - 无法从派生类构造函数参数访问受保护的基类成员
- jquery - 我们如何从父 div 中删除最近的 div