【问题标题】:How to store the textbox data (from react.js) into mongoDB using node.js如何使用 node.js 将文本框数据(来自 react.js)存储到 mongoDB
【发布时间】:2021-06-17 22:12:14
【问题描述】:

如何使用 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>
  );
}

【问题讨论】:

    标签: javascript node.js reactjs mongodb express


    【解决方案1】:

    前端

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 2012-08-04
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多