When I am making a post request from react, it sends a null value to the database.
So, I put log statements everywhere and it seems that : on the server side in nodejs, the const {firstName} is undefined and I do not understand why. Also, I log the req on the server-side and the body is empty body:{}.
Client side: when I put log statement in try block on body, it log me this: firstName: "abc" . So, the POST method does receive the body, but I do not understand where it gets lost?
When I console.log the state, it does set the state to the input value. However, when it sends data, the value is null.
I am using the following Reactjs, Nodejs, aws-rds-postgresql.
This is sever-side in nodejs
app.post("/users", async (req, res) => {
try {
const {firstName} = req.body;
console.log({firstName})
const newUser = await pool.query(
"INSERT INTO users (firstname) VALUES ($1) RETURNING *",
[firstName]
);
res.json(newUser.rows[0]);
}catch (err) {
console.log(err.message);
}
});
This is client side in react:
const CreateEmployee = (props) => {
const [firstName, setEmployeeForm] = useState("");
const onSubmitForm = async (event) => {
event.preventDefault();
try {
const body = {firstName};
console.log(body);
const response = await fetch("http://localhost:5000/users", {
method: "POST",
headers: {"Content-Type": "application/json"},
// We convert the React state to JSON and send it as the POST body
body: JSON.stringify(body)
});
console.log(response);
} catch (err) {
console.log(err.message);
}
}
return (
<Fragment>
<h1 className="text-center mt-5">PernTodo</h1>
<form className="d-flex mt-5" onSubmit={onSubmitForm}>
<input type="text" className="form-control" value={firstName} onChange={e=> setEmployeeForm(e.target.value)}/>
<button className="btn btn-success">Add</button>
</form>
</Fragment>
);
}
export default CreateEmployee;
question from:
https://stackoverflow.com/questions/66050853/post-request-sends-null-value-to-the-database-postgresql-react-node 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…