我是一个初学者,我正在试图弄清楚如何将react中的函数生成的变量发送到后端服务器端。
用户单击一个按钮,在home.jsx中生成一个名为rowObject的json对象。我想将它发送到后端到post.js以保存到数据库中。我该如何实现这一点?
发布于 2021-11-13 21:32:23
您的前端将向您的服务器发出请求,可能使用类似于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}`)
})
https://stackoverflow.com/questions/69960489
复制