我正在用next.js构建一个web应用程序,并将其托管在Vercel上。我已经在Vercel中设置了一个数据库集群,我可以在开发中(从本地主机)和从MongoDB compass连接到它,但是当我将它部署到MongoDB时,client.connect()给我一个HTTP502错误。
为什么我可以从本地主机连接,但不能从我的Vercel部署的应用程序连接?根据Atlas仪表板上的连接说明,我的连接字符串是mongodb+srv://<username>:<password>@testcluster.i2ddc.mongodb.net/data?retryWrites=true&w=majority。
发布于 2020-10-05 17:19:30
您是否已将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可能会很有用
发布于 2021-07-30 06:01:11
试试这段代码可能会有帮助。
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});}
});
})
});https://stackoverflow.com/questions/64078009
复制相似问题