mongodb - 在“下一次构建”期间 ECONNREFUSED。适用于“下一个开发”
问题描述
我有一个非常简单的 NextJS 9.3.5 项目。目前,它有一个页面/用户和一个pages/api/users
从本地 MongoDB 表中检索所有用户的页面
它使用'next dev'在本地构建良好但是,它在'next build'上失败并出现ECONNREFUSED错误
页面/用户
import fetch from "node-fetch"
import Link from "next/link"
export async function getStaticProps({ params }) {
const res = await fetch(`http://${process.env.VERCEL_URL}/api/users`)
const users = await res.json()
return { props: { users } }
}
export default function Users({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user._id}`}>
<a>{user.name}</a>
</Link>
</li>
))}
</ul>
);
}
页面/api/用户
import mongoMiddleware from "../../lib/api/mongo-middleware";
import apiHandler from "../../lib/api/api-handler";
export default mongoMiddleware(async (req, res, connection, models) => {
const {
method
} = req
apiHandler(res, method, {
GET: (response) => {
models.User.find({}, (error, users) => {
if (error) {
connection.close();
response.status(500).json({ error });
} else {
connection.close();
response.status(200).json(users);
}
})
}
});
})
纱线构建
yarn run v1.22.4
$ next build
Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
> Info: Loaded env from .env
Creating an optimized production build
Compiled successfully.
> Info: Loaded env from .env
Automatically optimizing pages ..
Error occurred prerendering page "/users". Read more: https://err.sh/next.js/prerender-error:
FetchError: request to http://localhost:3000/api/users failed, reason: connect ECONNREFUSED 127.0.0.1:3000
任何想法出了什么问题?特别是当它与“下一个开发”一起工作时?
谢谢你。
解决方案
几天前我也尝试过,但没有成功...因为当我们构建应用程序时,我们没有可用的本地主机...检查文档的这一部分 - https://nextjs.org/docs/basic -features/data-fetching#write-server-side-code-directly - 说:“你不应该从 getStaticProps 获取 API 路由......” -
(Next.js 9.3.6)
推荐阅读
- swift - 如何在 swift iOS 应用程序中允许 gboard?
- r - 在 ARIMA 或 ETS 预测后为最终结果添加季节性和非平稳性
- android - Android Studio:默认语言
- javascript - 更改文本背景荧光笔
- suitescript - SuiteScript 加载保存的搜索并添加过滤器会引发错误
- linux - 一次重启多个服务的Shell脚本
- php - 如何访问 htdocs 文件夹之外的 XAMPP mysql 数据库
- java - Java根据属性对对象进行排序
- java - 转换为 JSON 时的堆栈溢出问题
- rust - 使用 Tokio 启动多个线程