【问题标题】:How to send a variable from react to node如何将变量从反应发送到节点
【发布时间】:2021-11-14 05:21:31
【问题描述】:

我是一个初学者,我正在尝试弄清楚如何将函数生成的变量发送到后端服务器端。

用户点击一个按钮,在 home.jsx 中生成一个名为 rowObject 的 json 对象。我想将它发送到后端 post.js 以将其保存到数据库中。我如何做到这一点?

【问题讨论】:

    标签: javascript node.js reactjs express mern


    【解决方案1】:

    您的前端会向您的服务器发出请求,可能会使用 the browsers built in fetch() function. 之类的东西

    例如:

    function MyComponent() {
      function onClick() {
        fetch(
          '/some/path/here',
          {
            method: 'POST',
            body: JSON.stringify({ myData: 123 })
          }
        )
      }
    
      return <div onClick={onClick}>Click Me</div>
    }
    

    然后在the backend in express 上你会得到类似的东西:

    const express = require('express')
    const app = express()
    const port = 3000
    
    app.post('/some/path/here', (req, res) => {
      dbOrSomething.saveSomewhere(req.body) // your implementation here
      res.send('Saved!')
    })
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`)
    })
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2020-08-18
      • 2019-01-14
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多