简体   繁体   中英

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.

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.

Your code on react client should look like this:

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.

You can use axios in this case

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

Please let me know if you need any help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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