【发布时间】:2022-08-04 20:37:44
【问题描述】:
MongoDB 连接在端口连接 3001 处被拒绝,它之前工作但突然停止工作。我的数据库在 MongoDB atlas 上。我通过 mongoDB compass 进行连接,并且我的代码中有连接链接。我完全遵循了一个 mern 教程,但仍然面临这个问题:https://www.youtube.com/watch?v=I7EDAR2GRVo。有谁知道为什么会发生这种情况?
import \"./App.css\";
import { useState, useEffect } from \"react\";
import Axios from \"axios\";
function App() {
const [listOfUsers, setListOfUsers] = useState([]);
const [name, setName] = useState(\"\");
const [age, setAge] = useState(0);
const [username, setUsername] = useState(\"\");
useEffect(() => {
Axios.get(\"http://localhost:3001/getUsers\").then((response) => {
setListOfUsers(response.data);
});
}, []);
const createUser = () => {
Axios.post(\"http://localhost:3001/createUser\", {
name,
age,
username,
}).then((response) => {
setListOfUsers([
...listOfUsers,
{
name,
age,
username,
},
]);
});
};
return (
<div className=\"App\">
<div className=\"usersDisplay\">
{listOfUsers.map((user) => {
return (
<div>
<h1>Name: {user.name}</h1>
<h1>Age: {user.age}</h1>
<h1>Username: {user.username}</h1>
</div>
);
})}
</div>
<div>
<input
type=\"text\"
placeholder=\"Name...\"
onChange={(event) => {
setName(event.target.value);
}}
/>
<input
type=\"number\"
placeholder=\"Age...\"
onChange={(event) => {
setAge(event.target.value);
}}
/>
<input
type=\"text\"
placeholder=\"Username...\"
onChange={(event) => {
setUsername(event.target.value);
}}
/>
<button onClick={createUser}> Create User </button>
</div>
</div>
);
}
export default App;
const express = require(\"express\");
const app = express();
const mongoose = require(\"mongoose\");
const UserModel = require(\"./models/Users\");
const cors = require(\"cors\");
app.use(express.json());
app.use(cors());
mongoose.connect(\"mongodb+srv://username:password@cluster0.md4aag2.mongodb.net/merntutorial?retryWrites=true&w=majority\");
app.get(\"/getUsers\", (req, res) => {
UserModel.find({}, (err, result) => {
if (err) {
res.json(err);
} else {
res.json(result);
}
})
});
app.post(\"/createUser\", async (req, res) => {
const user = req.body;
const newUser = new UserModel(user);
await newUser.save();
res.json(user);
});
app.listen(3001, () => {
console.log(\"SERVER RUNS PERFECTLY!\");
});
-
发布凭据是个坏主意。