如何使用node.js将文本框数据(来自react.js)存储到mongoDB中



如何使用node.js将文本框数据(来自react.js(存储到mongoDB中?

我想在人们点击按钮后立即存储文本(应该存储在mongoDB云中(。所有连接都成功。

这是我的代码

App.js(在服务器中(

const mongoose = require("mongoose");
const express = require("express");
const app = express();
// Connection URL
const url = "mongodb+srv://dbname:pass@cluster0.gkqcs.mongodb.net/myApp?etryWrites=true&w=majority";
// Use connect method to connect to the Server
mongoose.connect(url,).then(() => 
{
console.log("connection successful");
}).catch((err) => console.log("not connected"));

App.js(前端使用react.js(

function App() {
return (
<div className="App">
<div className="container">
<div className="eleContainer">
<input type="text" className="txtAdd" placeholder="Type New Word"/>
<button className="addNew">Add to Dictionary</button>
<br />
<br />
<input type="text" className="searchWords" placeholder="Search here"/>
<br />
<br />
<ol className="vocabularyList">
<li>words</li>
</ol>
</div>
</div>
</div>
);
}

前端

function App() {
const [textAddValue, updateInput] = useState("");
const addNewText = () =>{
//send form data to server.
//use library like axios.
if(!textAddValue){ alert('input empty'); return;}
fetch('http://localhost:5000/sendText', {
headers: {
'Cache-Control': 'no-cache',
"Content-Type": "application/json",
'Accept': "application/json",
},
method: "POST",
body: JSON.stringify({text: textAddValue})
})
.then(res=>res.json())
.then(result=>console.log(result))
.catch(err=>{console.log(err)})
}
return (
<div className="App">
<div className="container">
<div className="eleContainer">
<input type="text" className="txtAdd" placeholder="Type New Word" value={textAddValue} onChange={(e)=>updateInput(e.target.value)}/>
<button className="addNew" onClick={addNewText}>Add to Dictionary</button>
<br />
<br />
<input type="text" className="searchWords" placeholder="Search here"/>
<br />
<br />
<ol className="vocabularyList">
<li>words</li>
</ol>
</div>
</div>
</div>
);
}

后端

const mongoose = require("mongoose");
const express = require("express");
const app = express();
//configure app for incoming post data
const expressJson = express.json();
const bodyParser  = express.urlencoded({extended: true});
app.use([expressJson, bodyParser])
// Connection URL
const url = "mongodb+srv://dbname:pass@cluster0.gkqcs.mongodb.net/myApp?etryWrites=true&w=majority";
// Use connect method to connect to the Server
mongoose.connect(url,).then(() => 
{
console.log("connection successful");
}).catch((err) => console.log("not connected"));

app.post('/sendText', (req, res)=>{
const text = req.body.text;
//you need to create mongoose schema to save. saveSchema here I'm asuming.
saveSchema.save({text: text})
.then(res=>{res.json("Saved")})
.catch(err=>{console.log(err); res.json("Error! cannot save")}
});
app.listen(5000, ()=>{console.log("Server running at port 5000")});

最新更新