【问题标题】:Post request sends null value to the database POSTGRESQL react nodePost 请求将空值发送到数据库 POSTGRESQL 反应节点
【发布时间】: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": &lt;something&gt; }。然后服务器试图从这个对象中拉出一个firstName 字段,但正如您所见,没有firstName 字段。 (我假设它是employeeForm 的一部分?)
  • 我全部改成了名字。当我在服务器端记录 {firstName} 时,它给了我未定义的信息。 {名字:未定义}
  • @AlexGrounds 我改写了这个问题

标签: node.js reactjs postgresql amazon-web-services amazon-rds


【解决方案1】:

我找到了答案。

问题在于正文解析器的顺序; 顺序必须如下,bodyParser 在最上面。

const bodyParser = require('body-parser');
const express = require("express");
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended: false}));

【讨论】:

    【解决方案2】:

    在 nodejs 中添加这一行对我有用:

    app.use(express.json())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      相关资源
      最近更新 更多