首页 > 解决方案 > 在“下一次构建”期间 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

任何想法出了什么问题?特别是当它与“下一个开发”一起工作时?

谢谢你。

标签: mongodbbuildhadoop-yarnnext.js

解决方案


几天前我也尝试过,但没有成功...因为当我们构建应用程序时,我们没有可用的本地主机...检查文档的这一部分 - https://nextjs.org/docs/basic -features/data-fetching#write-server-side-code-directly - 说:“你不应该从 getStaticProps 获取 API 路由......” -

(Next.js 9.3.6)


推荐阅读