简体   繁体   English

如何将数据从反应前端传递到节点快递后端?

[英]How do I pass data from react front end to node express backend?

I have just built an app and I wanted to be able to send data from my OnSubmit function to the express backend and store it there.我刚刚构建了一个应用程序,我希望能够将数据从我的 OnSubmit 函数发送到 express 后端并将其存储在那里。

Here is my server code:这是我的服务器代码:

const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));

app.get('/home', function (req, res) {
 return res.send('home');
});

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(process.env.PORT || 8080);

Pick one HTTP client, I recommend axios for ease of use. 选择一个HTTP客户端,我推荐axios易于使用。

Your code on react client should look like this: 您在react客户端上的代码应如下所示:

const respone = axios.post('http://localhost:8080/<your_endpoint>', {
  generalDetail: this.state.generalDetails,
  firstName: this.state.firstName,
  middleName: this.state.middleName,
  lastName: this.state.lastName
})

Then, you resolve response and take the data, it's promise object. 然后,您解决响应并获取数据,它是promise对象。

You can use axios in this case 在这种情况下,您可以使用axios

Example

saveData = e => {
        e.preventDefault();
        let data = {
              generalDetail: this.state.generalDetails,
              firstName: this.state.firstName,
              middleName: this.state.middleName,
              lastName: this.state.lastName
        };

        axios.post("http://localhost:8080/endpoint", data).then(() => {
           //do something
         }).catch(() => {
            console.log("Something went wrong. Plase try again later");
        });
    }

Change the endpoint to your api endpoint 将端点更改为api端点

Please let me know if you need any help 如果您需要任何帮助,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM