我正在next.js中构建一个Web应用程序并将其托管在Vercel上。我已经在MongoDB Atlas中建立了一个数据库集群,可以在开发中(从本地主机)和MongoDB指南针连接到该数据库集群,但是当我将其部署到Vercel时,int main(void) {
char name[sizeof("MatthewGamer") + sizeof("PlayGames") - 1] = "MatthewGamer"; char name2[] = "PlayGames";
printf("%s\n", add_str(name, name2));
}
会给我一个HTTP 502错误。
我是否可以从本地主机而不是从Vercel部署的应用程序进行连接?根据Atlas仪表板上的连接说明,我的连接字符串为client.connect()
。
答案 0 :(得分:1)
您是否已在MongoDb仪表板的网络访问配置中将Vercel ip添加到白名单?您可以尝试添加中间件进行连接,并捕获任何错误。我也可以尝试在连接字符串中不使用“ 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可能有用
答案 1 :(得分:0)
试试这个代码可能会有所帮助。
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});}
});
})
});