【发布时间】:2021-05-09 01:29:18
【问题描述】:
当我从 react 发出一个 post 请求时,它会向数据库发送一个空值。
所以,我到处都放了日志语句,似乎:在 nodejs 的服务器端,const {firstName} 是未定义的,我不明白为什么。另外,我在服务器端记录请求,正文为空正文:{}。
客户端:当我将 log 语句放在主体上的 try 块中时,它会记录我: firstName: "abc" 。那么,POST 方法确实接收到了 body,但我不明白它在哪里丢失了?
当我 console.log 状态时,它确实将状态设置为输入值。但是,当它发送数据时,该值为null。
我正在使用以下 Reactjs、Nodejs、aws-rds-postgresql。
这是 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);
}
});
这是反应中的客户端:
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;
【问题讨论】:
-
我会尝试在服务器端记录整个
req.body以更好地理解其结构。但乍一看,您好像在发送一个结构体{ "employeeForm": <something> }。然后服务器试图从这个对象中拉出一个firstName字段,但正如您所见,没有firstName字段。 (我假设它是employeeForm的一部分?) -
我全部改成了名字。当我在服务器端记录 {firstName} 时,它给了我未定义的信息。 {名字:未定义}
-
@AlexGrounds 我改写了这个问题
标签: node.js reactjs postgresql amazon-web-services amazon-rds