直接从React应用程序访问数据库通常不是一个推荐的做法,因为这会将数据库凭据暴露在客户端,存在严重的安全风险。传统的最佳实践是通过API层(如Node.js/Express、Django等)来访问数据库。
MongoDB Realm提供了安全的客户端直接访问方式:
import * as Realm from "realm-web";
const app = new Realm.App({ id: "your-realm-app-id" });
async function login() {
const credentials = Realm.Credentials.anonymous();
const user = await app.logIn(credentials);
return user;
}
async function getData() {
const user = await login();
const mongo = app.currentUser.mongoClient("mongodb-atlas");
const collection = mongo.db("your-db").collection("your-collection");
return await collection.find({});
}
Firebase提供了类似数据库的直接客户端访问方式,但内置了安全规则。
如果必须避免构建完整API,可以考虑以下轻量级方案:
// 例如使用云函数
const MongoClient = require('mongodb').MongoClient;
exports.main = async (event, context) => {
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const collection = client.db("your-db").collection("your-collection");
const result = await collection.find({}).toArray();
await client.close();
return result;
};
然后在React中调用:
fetch('your-serverless-function-url')
.then(response => response.json())
.then(data => console.log(data));
可以使用Hasura或Apollo Server快速搭建GraphQL层。
如果坚持直接从React访问MLab MongoDB,至少应该:
const { MongoClient } = require('mongodb');
// 注意: 这会将凭据暴露在客户端!
const uri = "mongodb+srv://username:password@cluster.mlab.com/dbname?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("sample_mflix");
const movies = database.collection("movies");
const query = { title: "Back to the Future" };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
await client.close();
}
}
run().catch(console.dir);
强烈建议构建一个简单的API中间层,即使是使用轻量级解决方案如:
这样可以确保数据库安全,同时提供更好的可维护性和扩展性。
没有搜到相关的文章