【问题标题】:Sending post request to backend returns empty req.body向后端发送 post 请求返回空的 req.body
【发布时间】:2023-03-11 22:33:01
【问题描述】:

我正在尝试将 react 连接到 express 服务器,但是当我尝试接收使用 react 应用程序发送的数据时,在后端的 req.body 中我得到一个空对象,这是我的反应代码:

export default function App() {
  let [text, setText] = useState("");
  const sendToServer = () => {
    axios
      .post("http://localhost:4000/test", {
        text: text
      })
      .then((res) => console.log(res))
      .catch((err) => console.log(err));
  };

  return (
    <div className="app">
      <input
        type="text"
        onChange={(e) => setText(e.target.value)}
      />
      <button onClick={sendToServer}>Send</button>
      <p>{text}</p>
    </div>
  );
}

这是我的后端:

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const cors = require('cors');

app.use(cors('http://localhost:3000'));

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

app.use("/test", (req, res, next) => {
    console.log(req.body);

});

app.use((req, res, next) => {
  console.log(`server listening`);
});

app.listen(4000);

我在 package.json 文件中使用了代理,但它仍然不起作用。 在 /test 请求中,我得到一个空对象。

【问题讨论】:

    标签: node.js reactjs express axios


    【解决方案1】:

    添加app.use(bodyParser.json({ limit: '10mb' }));

    【讨论】:

    • @Chrissisbeast 恳请您将此标记为答案。
    • 恳请您仔细检查这项工作,下面的建议更改使用->发布也是必要的。
    【解决方案2】:

    app.use 更改为app.post

    app.post("/test", (req, res, next) => {
        console.log(req.body);
    });
    

    参考文档Express Routing

    【讨论】:

      【解决方案3】:

      也许你应该添加 res.data 而不是 res

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-23
        • 2013-03-09
        • 2014-12-01
        • 1970-01-01
        • 2021-03-08
        • 1970-01-01
        • 1970-01-01
        • 2012-08-15
        相关资源
        最近更新 更多