在“下一次构建"期间 ECONNREFUSED.适用于“下一个开发" [英] ECONNREFUSED during 'next build'. Works fine with 'next dev'
问题描述
我有一个非常简单的 NextJS 9.3.5 项目.目前,它只有一个页面/用户和一个 pages/api/users
,用于从本地 MongoDB 表中检索所有用户
I have a very simple NextJS 9.3.5 project.
For now, it has a single pages/users and a single pages/api/users
that retrieves all users from a local MongoDB table
使用next dev"在本地构建良好但是,它在下一次构建"时失败并出现 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
任何想法出了什么问题?特别是当它与下一个开发者"配合良好时?
Any ideas what is going wrong ? particularly when it works fine with 'next dev' ?
谢谢.
推荐答案
我前几天也试过了,还是不行...因为当我们构建应用程序时,我们没有可用的本地主机...检查文档的这一部分 - https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly - 表示:您不应该从 getStaticProps 获取 API 路由..." -
I tried the same few days ago and didn't work... because when we build the app, we don't have localhost available... check this part of the doc - https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly - that said: "You should not fetch an API route from getStaticProps..." -
(Next.js 9.3.6)
(Next.js 9.3.6)
这篇关于在“下一次构建"期间 ECONNREFUSED.适用于“下一个开发"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!