我终于涉足了服务器端 React 的世界,使用 Next.js ,但是我对这个问题感到很困惑。
我正在使用 isomorphic-unfetch
从 pages/customer-preferences.tsx
调用 API
CustomerPreferencesPage.getInitialProps = async () => {
const res = await fetch(API_URL + '/preference-customer');
const initialData = await res.json();
return { initialData };
};
在dev
模式下,或者一旦构建并运行build
>start
后,一切都可以在本地正常工作。为了托管它,我从 docker 容器 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
任何帮助将不胜感激。
最佳答案
不,不需要服务器设置。
发生这种情况是因为浏览器/客户端无法解析您的 Docker 容器的主机名。就目前情况而言,我所知道的唯一解决方案是检查 getInitialProps 中的 req 对象(以便确定 fetch 将在哪个环境中运行),并在服务器上调用 Docker 主机名,在客户端上调用 localhost。例如。
async getInitialProps (ctx) {
if (ctx.req) // ctx.req exists server-side only
{
// call docker-host:port
}
else {
// call localhost:port
}
}
关于node.js - Next.js 服务器端 api 调用返回 500 内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59888240/