我使用MongoDB作为我的Reactjs项目的数据库。在这里,当我试图连接数据库时,它会给出一个错误--“未处理的拒绝(TypeError):无法读取未定义的属性‘替换’”
这是App.js的代码
import React from "react";
import Sidebar from "./Sidebar";
import Feed from "./Feed";
import Widgets from "./Widgets";
import "./App.css";
import { MongoClient } from "mongodb";
function App() {
// Connection URI
const uri =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("posts").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run();
return (
<div className="app">
<Sidebar />
<Feed />
<Widgets />
</div>
);
}
export default App;任何帮助都是非常感谢的!
发布于 2021-02-11 08:47:53
您需要为您的React应用程序创建一个后端,并从那里连接到数据库。然后公开一个端点,如/api/post,并在您的React中使用fetch或其他类似的方法调用它。
fetch('http://localhost:4000/api/posts')
.then(response => response.json())
.then(posts => console.log(posts));https://stackoverflow.com/questions/66149025
复制相似问题