首页 > 解决方案 > 如何使用 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>
  );
}

标签: javascriptnode.jsreactjsmongodbexpress

解决方案


前端

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")});

推荐阅读