首页 > 解决方案 > 在 Vercel 上部署的 Nextjs 中的 api 请求出现 504/502 错误

问题描述

我在 Next.js 中开发了一个应用程序。对于后端,我使用了 Nextjs 中配置的 api 端点,它们位于pages/api. api 端点经常返回 502(网关超时错误)或 504(我们的部署存在问题)。

通过一些研究,我发现它正在发生,因为服务器超时。对于我部署了 Nextjs 应用程序的 Vercel,无服务器功能的超时最大期限为 10 秒。

端点之一的代码(https://bulkbays.com/api/fetchSections)是

import db from "../../config/db";
import Section from "../../Models/Section";

db();

export default async function handler(req, res) {

    console.log('Entered the serverless function')

    Section.find()
        .lean()
        .then((sections) => {
            console.log('Fetched Sections',sections)
            return res.json(sections);
        })
        .catch((err) => {
            console.log('Error in fetching sessions',err)
            return res.json({
                status: false,
                msg: "An unexpected problem occured",
                err,
            });
        });
}

请有人告诉我怎么可能超过 10 秒。它是人们可以进行的最简单的查询。此外,此查询的结果只是一个长度为 9 的数组,其中对象作为项目,其值是字符串。它看起来像这样

[
  {
  "_id":"6092a55478ccc2092c5e41b0",
  "images":["http://res.cloudinary.com/bulkbays97/image/upload/v1620223428/eysvsch2hf4ymajizzcn.jpg","http://res.cloudinary.com/bulkbays97/image/upload/v1620223429/qiwa2idfrntiygsfmnx2.jpg","http://res.cloudinary.com/bulkbays97/image/upload/v1620223429/elwhjk7abwcde7ccqcxf.jpg","http://res.cloudinary.com/bulkbays97/image/upload/v1620223428/yuzhe8iehcyj1rmfyr09.jpg"],
  "title":"P-Caps",
  "createdAt":"2021-05-05T14:01:56.626Z",
  "updatedAt":"2021-05-05T14:01:56.626Z","__v":0
  },
  ....
]

这是发送 502 或 504 响应的请求之一的日志

[GET] /api/fetchSections
14:36:34:38
Status:-1
Duration:10010.32 ms
Init Duration: N/A
Memory Used:60 MB
ID:x7lh8-1620552994128-a44f049a01ae
User Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0
2021-05-09T09:36:44.511Z 62c16977-9c5c-42f5-961f-a63083638a9c Task timed out after 10.01 seconds

请指导我。我应该怎么办?我应该为此使用 Heroku(不是无服务器)之类的东西还是什么?

我为客户制作了这个网站,现在我不知道是什么问题导致了这个问题。

标签: node.jslambdanext.jsserverlessvercel

解决方案


作为不断研究的结果,我所做的是将 API 发布在 Heroku 上,将前端发布在 Vercel 上。我在一篇 stackoverflow 帖子中从一个说他在 Vercel 工作的人那里读到了这个建议,这是最合适的解决方案。

我认为这是无服务器架构本身的问题。我尝试在 netlify 上部署 Nextjs 并遇到了类似的情况。


推荐阅读