将数据从反应传递到节点快速服务器

时间:2019-05-15 00:03:04

标签: node.js reactjs express

我试图将数据从我的响应前端从onSubmit函数传递到我的节点/表达服务器。

控制台上和页面上没有显示数据,只是说“未定义”,有人可以帮帮我吗?

App.js文件

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;

服务器

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}`);

1 个答案:

答案 0 :(得分:0)

您的onSubmit使用let变量。因此它将不在该功能的范围之内。