【问题标题】:Next.JS: Can't call Internal API in getInitialProps. Got Error: read ECONNRESETNext.JS:无法在 getInitialProps 中调用内部 API。出现错误:读取 ECONNRESET
【发布时间】:2019-01-29 00:29:36
【问题描述】:

当我在 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。

请帮忙!我的代码有问题吗?我正在搜索过去几个小时,但无法解决。

【问题讨论】:

标签: javascript reactjs express next.js


【解决方案1】:

您可以从请求中提取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')
    ...
}

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2023-01-26
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多