Home > Enterprise >  Can't access the data property of the response in React
Can't access the data property of the response in React

Time:12-17

I have two pages, register and status. From the register page, I submit a form and when I get the response I want to send it to the status page and access some of the properties of the object.

    const register = (e) => {
    e.preventDefault();

    Axios.post("http://localhost:3001/register", {
        name : name,
        NID : NID,
        birth : birth,
        phone : phone,
        gender : gender,
        center : center,
        address : address
    }).then((response) => {
        console.log(response.data);
        setResponse(response.data.NID);
    });
    e.target.reset();
};

The post request is successful every time in the MySQL database. But when I console log the response.data I don't get the data properties. enter image description here

The backend:

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

  const name = req.body.name;
  const NID = req.body.NID;
  const birth = req.body.birth;
  const phone = req.body.phone;
  const gender = req.body.gender;
  const center = req.body.center;
  const address = req.body.address;

  db.query(
    "insert into register (name, NID, birth, phone, gender, center, address) values (?,?,?,?,?,?,?)",
    [name, NID, birth, phone, gender, center, address],
    (err, result) => {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Also, on rendering {response.data.name} I get an error.

CodePudding user response:

What you're logging is what your server is returning as a response. You'll need to return what you need in the response from your backend app. So instead of res.send(result) where result is the result of the db query, call res.send with whatever data you want to send to the frontend.

Or if what you need is in the request parameters, just wait for the request to succeed (like in your code sample) and use the request parameters. I.e. instead of setResponse(response.data.NID) use setResponse(NID) - you already have "NID" as a variable in your code sample.

CodePudding user response:

What do your backend returns ? Is it just a response.status 201 ? Is the body empty ? You should check in the Network tab of the devtools what happens when you hit that endpoint.

HTTP Status codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

  • Related