Vercel 上的 Nextjs 部署 - API 请求返回 500,适用于 localhost

Ada*_*šák 5 javascript reactjs next.js vercel

我将 Nextjs 应用程序部署到 Vercel,但我的 api 调用失败,响应为 500,即使它在 localhost 上运行也是如此。我可以使用 获得初始负载getStaticProps,所以我相信与数据库的连接是可以的。

我的getStaticPaths功能正常工作如下所示:

export async function getStaticProps() {
  dbConnect();
  const properties = await Property.find({
    deletedAt: { $exists: false },
    archivedAt: { $exists: false },
  })
    .sort({ refreshed: -1 })
    .limit(itemsPerPage);
  const propertiesCount = await Property.countDocuments(
    { deletedAt: { $exists: false }, archivedAt: { $exists: false } },
    { limit: 100 }
  );
  const pagesCount = Math.ceil(propertiesCount / itemsPerPage);

  return {
    props: {
      fetchedProperties: properties.map((property) => propertyToJson(property)),
      pagesCount: pagesCount,
    },
    revalidate: 5,
  };
}
Run Code Online (Sandbox Code Playgroud)

但是,当查询发生变化时,我会useEffect像这样调用钩子:

useEffect(() => {
    if (Object.keys(query).length > 0) {
      (async () => {
        const filteredProperties = await fetch(
          process.env.NEXT_PUBLIC_BASE_URL +
            '/api/properties?' +
            new URLSearchParams(query)
        );
        const res = await filteredProperties.json();

        if (res.status === 200) {
          setProperties(res.properties);
        } else {
          //show error
          console.log('error');
        }
      })();
    }
  }, [query]);
Run Code Online (Sandbox Code Playgroud)

这总是返回错误(在本地主机上工作)。我的pages/api/properties/index.js文件看起来像这样:

import dbConnect from 'utils/dbConnect';
import Property from 'models/Property';
import { propertyToJson } from 'utils/helpers';

const handler = async (req, res) => {
  console.log('req:', req);
  const { method } = req;
  dbConnect();
  if (method === 'GET') {
    const { price } = req.query;

    let queryCond = {};
    if (price) {
      queryCond.price = { $lte: price * 1 };
    }
    console.log('queryCond:', queryCond);

    try {
      const properties = await Property.find(queryCond).exec();
      console.log('properties:', properties);

      res.status(200).json({
        status: 200,
        properties: properties,
      });
    } catch (err) {
      res.status(500).json(err);
    }
  }
};

export default handler;
Run Code Online (Sandbox Code Playgroud)

此外,我无法console.log从任何地方看到该 api 文件。不在 Vercel 函数日志中,在运行时不在我的终端中vercel dev --debug。我有一种感觉,该请求甚至没有到达该api/properties/index.js文件......

如果您能帮助我解决这个问题,我将非常感激,但如果您能指出如何有效地调试这些 api 文件,我将更加感激。谢谢。

Ada*_*šák 5

我明白了这一点。我的方法有两个问题:

  1. 我提供的代码片段只是更复杂代码的一部分。import { adminAuth } from 'config/firebase-admin'有一个“POST”方法的一部分,我在问题中省略了它,并且存在 env 变量配置不正确的导入。我认为这部分应该不会有问题,因为我没有调用该方法的这部分。
  2. 当然,我甚至使用问题中的代码进行了测试,但看起来它可能缓存在我的浏览器中并且反映了较旧的版本。对于 Vercel 上的每个构建,都会生成 3 个 url,并且最好选择包含令牌的 url,因此它对于构建来说是唯一的,并且您不可能查看缓存的旧代码。