ECONNREFUSED在'next build'期间进行。与'next dev'

问题描述 投票:1回答:1

我有一个非常简单的NextJS 9.3.5项目。目前,它只有一个页面/用户和一个pages/api/users,可从本地MongoDB表中检索所有用户

它使用'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

任何想法出了什么问题?特别是当它与'next dev'正常工作时?

谢谢。

mongodb build yarn next.js
1个回答
1
投票

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

((Next.js 9.3.6)

© www.soinside.com 2019 - 2024. All rights reserved.