首页 > 解决方案 > Next.js 服务器端 api 调用返回 500 内部服务器错误

问题描述

我终于开始使用Next.js进入服务器端反应的世界,但是我对这个问题感到很困惑。

我正在通过使用调用pages/customer-preferences.tsxAPIisomorphic-unfetch

CustomerPreferencesPage.getInitialProps = async () => {
  const res = await fetch(API_URL + '/preference-customer');
  const initialData = await res.json();
  return { initialData };
};

一切都在本地dev模式下正常工作,或者一旦构建并运行build> start。为了托管它,我从 docker container 运行它node:10,当我在本地运行它时,一切都很好。该问题仅在部署后发生。

当我按预期导航到/然后单击指向/customer-preferences所有作品的链接时。但是,如果我刷新页面或直接加载页面,/customer-preferences我会从 Next.js 看到此错误

在此处输入图像描述

所以这个问题似乎只发生在尝试从服务器而不是客户端进行 API 调用时。

我还设置了一个简单的快速服务器来代替使用,但不确定这是否有必要?!

const express = require('express');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

检查服务器日志时,我得到以下信息:

FetchError: request to http://xxx failed, reason: getaddrinfo EAI_AGAIN xxx xxx:80

任何帮助将不胜感激。

标签: node.jsreactjsdockernext.jsserver-side-rendering

解决方案


不,不需要服务器设置。

发生这种情况是因为浏览器/客户端无法解析您的 docker 容器的主机名。就目前而言,我知道的唯一解决方案是检查 req 对象getInitialProps(以确定提取将在哪个环境中运行)并在服务器上调用 Docker 主机名,在客户端调用 localhost。例如

async getInitialProps (ctx) {
    if (ctx.req) // ctx.req exists server-side only
    {
        // call docker-host:port
    }
    else {
        // call localhost:port
    }
}

推荐阅读