简体   繁体   中英

Trying to pass data from react(front end) to node server(backend)

I'm trying to pass data from my react end from my onSubmit function to my node/express server.

Data is not showing up in the console and on the page as it just says "undefined" Could someone please help me out? Thanks!

App.js file

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      generalDetails: "Text",
      fName: "Text",
      mName: "Text",
      LName: "Text",
      gender: "Text"
    };

    this.onContentChange = this.onContentChange.bind(this);
    this.onSubmitForm = this.onSubmitForm.bind(this);
  }

  render() {
    return (
      <div className="App">
        <PageOne handleChange={this.onContentChange} />
        <PageTwo handleChange={this.onContentChange} />
        <PageThree handleChange={this.onContentChange} />
        <PageFour handleChange={this.onContentChange} />
        <PageFive handleChange={this.onContentChange} />
        <PageSix handleChange={this.onContentChange} />

        <Button onClick={this.onSubmitForm}>Submit Form</Button>

        <br />
        <br />
      </div>
    );
  }

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

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


  onContentChange(fieldname, data) {
    console.log("On Content Change", data);

    this.setState({
      [fieldname]: data
    });
  }
}

export default App;

Server

const express = require("express");
const app = express();
const port = 5000;

const cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
  bodyParser.urlencoded({
    // to support URL-encoded bodies
    extended: true
  })
);

app.get("/home", (req, res) => {
    console.log("Hello from .get /home", req.body.generalDetails );

})




app.post("/home", (req, res) => {

  const data = [{ generalDetails: req.body.generalDetails }];


  res.json(data);
});

app.listen(port, () => `Server running on port ${port}`);

Your question is very vague so I will try to answer to the best of my ability just by taking a look at your code. Where are you getting undefined from? Where are you trying to log to the console? And are you getting any errors in your browser console and/or your node console? These are questions I have about your question but here is what I think your problem is.

If you are trying to send a get request from your front end and are trying to receive it at

app.get("/home", (req, res) => {
  console.log("Hello from .get /home", req.body.generalDetails );
})

then you need to send a get request from your front end and not a post request. Right now your axios function is making a post request so it will be received in your backend at the post route and not the get route.

If what your are trying to do is make a post request then you will receive it at the post route and what your code does now is send generalDetials back. The problem is that you have an empty function receiving the request back from your server. Whether you are making a post or get request you need to then do something with that information.

So do the following so you can see what is happening. Make a post request and then log the response to your browsers console:

axios
  .post("http://localhost:5000/home", data)
  .then(result => {
    console.log(result)
  })
  .catch(() => {
    console.log("Something went wrong. Please try again later");
  });

If you are getting the general details back in the axios data then you are successfully making a post request.

Then make a get request:

axios
  .get("http://localhost:5000/home", data)
  .then(result => {
    console.log(result)
  })
  .catch(() => {
    console.log("Something went wrong. Please try again later");
  });

If you are logging the information in your node console then you are making your get request successfully. Because in your backend your only logging to the console in the get route.

Also it looks like you have a syntax error. You forgot to close the onSubmitForm function. Your missing the closing curly bracket.

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