簡體   English   中英

Vercel 上的 Nextjs 部署 - api 請求返回 500,適用於 localhost

[英]Nextjs deployment on Vercel - api requests return 500, works on localhost

我將我的 Nextjs 應用程序部署到 Vercel 並且我的 api 調用失敗並顯示響應 500,即使它在 localhost 上運行也是如此。 我可以使用getStaticProps獲得初始負載,所以我相信與數據庫的連接是可以的。

我的getStaticPaths function 正常工作看起來像這樣:

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,
  };
}

但是,當查詢更改時,我會像這樣調用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]);

這總是返回錯誤(在本地主機上工作)。 我的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;

此外,我無法在任何地方從 api 文件中看到console.log 不在 Vercel function 日志中,不在我的終端中運行vercel dev --debug 我有一種感覺,請求甚至沒有到達那個api/properties/index.js文件......

如果您能幫助我解決這個問題,我將不勝感激,但如果您能指出如何有效地調試這些 api 文件,我將更加感激。 謝謝。

我想通了。 我的方法有兩個問題:

  1. 我提供的代碼片段只是更復雜代碼的一部分。 我在問題中省略了“POST”方法的一部分,並且import { adminAuth } from 'config/firebase-admin'其中 env 變量配置不正確。 我認為這部分不應該是問題,因為我沒有調用該方法的這一部分。
  2. 當然,我甚至使用問題中的代碼進行了測試,但看起來它可能緩存在我的瀏覽器中並且它反映了舊版本。 對於 Vercel 上的每個構建,都會生成 3 個 url,對於 go 來說,它可能是最好的,其中包含令牌 - 所以它對於構建來說是唯一的,而且您沒有機會查看緩存的舊代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM