node.js - Next.js 服务器端 api 调用返回 500 内部服务器错误
问题描述
我终于开始使用Next.js进入服务器端反应的世界,但是我对这个问题感到很困惑。
我正在通过使用调用pages/customer-preferences.tsx
APIisomorphic-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
任何帮助将不胜感激。
解决方案
不,不需要服务器设置。
发生这种情况是因为浏览器/客户端无法解析您的 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
}
}
推荐阅读
- ios - 如何在快速点击复选框时仅增加一次计数?
- javascript - Javascript:按频率对数组中的元素进行排序
- javascript - res.render() 未显示
- magento - 无法理解何时在 magento 中调用“salesrule_rule_condition_combine”挂钩?
- java - LSTM 和密集层预处理
- python - Python 无法安装包
- python - 在运行时为云函数 GCP 重命名 python 函数 def
- javascript - 可点击的按钮和改变 div 的内容
- micro-frontend - 在选项卡下渲染 pilet
- c# - C# 代码中的 .bat 脚本,它一直试图逃避我的原始代码