如何将变量从反应发送到节点

How to send a variable from react to node

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

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

您的前端会向您的服务器发出请求,可能使用类似 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}`)
})