我有一个 react 网站,应该从我的 mongodb atlas 数据库中查询数据并将其显示给用户。在我的 atlas 集群中,我已经使用密码 readuser
和 readall-permissions 创建了一个用户 readuser
。
正在关注 the official guide ,我试试这个:
import React from 'react';
import MongoClient from 'mongodb';
function App() {
var uri = "mongodb+srv://readuser:readuser@personalwebsite-oerah.mongodb.net/test?retryWrites=true&w=majority";
var client = new MongoClient(uri, {useNewUrlParser : true});
client.connect(err => {
console.log(err);
client.close();
});
return (<p>Hello world</p>);
}
export default App;
但是, react 显示错误 Uncaught TypeError: Cannot read property 'replace' of undefined at matchesParentDomain (uri_parser.js:24)
- 是 node js solution适合我的问题? (它似乎更多地用于后端应用程序)
- 是否可以让我的数据库公开可读以避免需要从我的应用程序登录?
- 如何修复错误?
我知道这听起来与 this thread 非常相似, 但我不使用 Mongoose ,所以问题有点不同。
最佳答案
官网给出的例子是针对nodejs的,不是react(clint side javascript)。 您需要使用 nodejs 或 PHP 或任何其他服务器端脚本创建后端 API 端点,然后使用 react 进行简单的提取以从您自己的端点获取数据。 这种方式也更安全,因为您不必在客户端 javascript 上公开您的数据库凭据。
关于javascript - 从 react 应用程序连接到 mongodb 给出 TypeError : Cannot read property 'replace' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848361/