Express-`req.body`始终为空

时间:2019-06-17 03:43:44

标签: node.js reactjs express mern

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

我尝试仅使用price = float(foot) * .075 app.use(bodyParser.json()),但没有任何变化。

index.js

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

utility_routes.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);

request.body

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 } } }

2 个答案:

答案 0 :(得分:2)

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", (req, res) => {
        console.log("Utility", req);
        console.log("Req Done");            
      });

答案 1 :(得分:0)

这就是我用来接受"clubs": [ { "key": "chelsea", "name": "Chelsea", "code": "CHE", "total_matches":38, "won":"21", "lost":"15", "ties":"2", "total-goals":"33", "scored-against":"28" }, { "key": "arsenal", "name": "Arsenal", "code": "ARS", "total_matches":38, "won":"21", "lost":"15", "ties":"2", "total-goals":"33", "scored-against":"28" }]

json

在请求集标头中是这样的。

var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();   
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
 })); 

 app.use(express.json());
 app.use(cookieParser());

angular的axios和http库都可以使用此设置。