服务器端代码在这里
async function run() { try { // Connect the client to the server (optional starting in v4.7) await client.connect(); const database = client.db("userDB"); const usersC = database.collection("users"); app.post('/user', async (req, res) => { const user = req.body; console.log(user); const result = await usersC.insertOne(user); console.log(
插入了带有_id的文档:${result.insertedId}) }) // Send a ping to confirm a successful connection await client.db("admin").command({ ping: 1 }); console.log("Pinged your deployment. You successfully connected to MongoDB!"); } finally { // Ensures that the client will close when you finish/error await client.close(); } }
客户端代码 ` const handalForm = event =>{ 事件.preventDefault(); 常量形式 = event.target;
const name = form.name.value;
const email = form.email.value;
const user ={name,email}
console.log(user);
fetch('http://localhost:5000/user',{
method:'POST',
headers: {
'content-type':'application/json'
},
body:JSON.stringify(user)
}).then(res=> res.json()).then(data=>{
console.log(data);
})
}`
可能是您的后端服务器已关闭或未在端口 5000 上运行。