node.js - Express - `req.body` 始终为空

标签 node.js reactjs express mern

我正在尝试构建一个完整的堆栈(MERN)应用程序。当我使用 JSON 向 Express 服务器发送请求时,我总是看到我的 req.body 为空。我在请求中无法看到我的 JSON。

我尝试仅使用 app.use(bodyParser.json())app.use(bodyParser.urlencoded({ Extended: true }));,但没有变化。

index.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
console.log("App");
require("./schema/data");
require("./routes/home_routes")(app);
require("./routes/table_routes")(app);
require("./routes/utility_routes")(app);

utility_routes.js

const mongoose = require("mongoose");
const Data = mongoose.model("data");
module.exports = app => {
  app.get("/api/search_member", (req, res) => {
    console.log("Utility", req);
    console.log("Req Done");
    // const search = await Data.findById({ member_id: req.body.member_id });
    // console.log(search);
  });
};

请求正文

[0]   body: {},
[0]   route:
[0]    Route {
[0]      path: '/api/search_member',
[0]      stack: [ [Layer] ],
[0]      methods: { get: true } } }

客户要求

 onSearch = async value => {
      console.log(value);
      if (value) {
        const searchData = await axios.get("/api/search_member", { value });
        console.log(searchData);
      }
    };

最佳答案

You are making a GET request. GET request do not send body. To get req.body, make POST request to server.

Firstly:-

    const searchData = await axios.post("/api/search_member", { value });

And Secondly,

     app.POST("/api/search_member", async (req, res) => {
        console.log("Utility", req);
        console.log("Req Done");            
      }); 

关于node.js - Express - `req.body` 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56624471/

相关文章:

javascript - 从多个类导出的 js 中 react 加载导入

javascript - 如何在问号后获取url中的变量输入(Javascript)

node.js - 如何在 express - node js 中使用集群的粘性 session

node.js - 使用 query-overpass 和 turf.js 将 geojson 多边形转换为带有 Node 的点

javascript - 使用 nodejs 和 knox 如何查看 S3 存储桶中的文件

javascript - 即使所有内容都已呈现,浏览器也会尝试加载

javascript - setState 的真实世界用法与更新回调而不是在 React JS 中传递对象

javascript - 在 Node.js 中获取客户端主机名

css - Node + React - 带连字符的 CSS 类名

javascript - 异步 mongoDB find() 方法的问题