Home > database >  Passing a state for an Axios POST request
Passing a state for an Axios POST request

Time:03-03

I want to pass a state into an axios post request, for the state data to get into my backend. But i get an error telling me the state that i chose is not defined.

Here's what i've got:

React frontend

    this.state = {
      spieler: "",
    };
  }

  submitName() {
    const body = spieler;
    Axios.post("http://localhost:3001/api/insert", {
      spieler: spieler,
    }).then(() => {
      console.log(this.state.spieler);
      alert("successful insert");
    });
  }

Node Backend

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/api/insert", (req, res) => {
  const spieler = req.body.spieler;

  const sqlInsert = "INSERT INTO spiele (spieler) VALUES (?)";
  db.query(sqlInsert, spieler, (err, result) => {
    console.log(result);
  });
});

Here is the result

undefined_error

CodePudding user response:

In your function submitName you are creating the body of the axios request using a variable spieler but it has not been defined previously. You should make use of spieler from state as follows:

submitName() {
  const body = { spieler: this.state.spieler };
  Axios.post("http://localhost:3001/api/insert", body).then(() => {
    console.log(this.state.spieler);
    alert("successful insert");
  });
}

CodePudding user response:

You are not accessing the real properties. replace

{
      spieler: spieler,
}

with

{
      spieler: this.state.spieler,
}
  • Related