MongoDB returns Vercel 托管应用中出现 502 错误

MongoDB returns 502 error in Vercel hosted app

我正在 next.js 中构建网络应用程序并将其托管在 Vercel 上。我在 MongoDB Atlas 中设置了一个数据库集群,我可以在开发中(从本地主机)和 MongoDB compass 连接到它,但是当我将它部署到 Vercel 时,client.connect() 给了我HTTP 502 错误。

为什么我可以从本地主机连接但不能从我的 Vercel 部署的应用程序连接?根据 Atlas 仪表板上的连接说明,我的连接字符串是 mongodb+srv://<username>:<password>@testcluster.i2ddc.mongodb.net/data?retryWrites=true&w=majority

您是否已将 Vercel ip 添加到 MongoDb 仪表板中网络访问配置的白名单?您可以尝试添加中间件进行连接,并捕获任何错误。我也会尝试在连接字符串中不使用“retryWrites=true”。

中间件

import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

export default async function database(req, res, next) {
  if (!client.isConnected()) await client.connect();
  req.dbClient = client;
  req.db = client.db(process.env.DB_NAME);
  await setUpDb(req.db);
  return next();
}

您只需要设置环境变量即可。 This tutorial 可能有用

试试这个代码可能会有帮助。

const Express = require("express");
const BodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const CONNECTION_URL = "mongodb+srv://id:password@portfolio.t6jry.mongodb.net/myinfo?retryWrites=true&w=majority";
const DATABASE_NAME = "info";

const port = process.env.PORT || 3000;

var app = Express();
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
var database, collection;

app.listen(port, () => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
        if(error) {
            throw error;
        }
        database = client.db(DATABASE_NAME);
        collection = database.collection("myinfo");
        console.log("Connected to `" + DATABASE_NAME + "`!");
    });
});

app.get("/", (req, res, next) => {
    return res.json({ message: "Server Running" });
  });

app.get("/info",async (request, response) => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {client.db("info").collection("myinfo").find({}).toArray((error, result)  => {
        if(error) {
            return response.json({ status: 500, message: "Internal Server Error" });
        }
        else if (!result) {
          return response.json({ status: 422, message: "Document Not Found" });}
        else{  return response.json({ status: 200, message: result});}
    });
})
});

app.post("/postdata",async (request, response) => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {client.db("info").collection("myinfo").find({}).toArray((error, result)  => {
        if(error) {
            return response.json({ status: 500, message: "Internal Server Error" });
        }
        else if (!result) {
          return response.json({ status: 422, message: "Document Not Found" });}
        else{  return response.json({ status: 200, message: result});}
    });
})
});