req.body始终是一个空对象

时间:2020-01-20 18:37:35

标签: node.js reactjs express

我正在做一个React App + Express服务器,

我想从客户端表单中获取服务器中所有信息的路由/ info,

但是当我在服务器中控制台登录“ req.body”时,我总是得到一个空对象(请参见下面的Express代码),

我尝试使用body解析器,但没有任何变化,我看不出问题出在哪里,

有人可以帮我吗?

反应代码:

async function getResults(e) {
    e.preventDefault();

    const info = {
      minimumPrice,
      maximumPrice
    };

    console.log("info ", info);

    try {
      const data = await axios.get("http://localhost:5000/info", info);
      console.log("data ", data);

      setResults(data.data);
      console.log("results ", data.data);
    } catch (e) {
      console.error(e);
    }
  }

<form onSubmit={getResults} autoComplete="off" method="get">
                <div className="row">
                  <div className="input-field col s12">
                    <input
                      id="minimum-price"
                      type="number"
                      name="minimumPrice"
                      placeholder="Entrez votre prix minimum"
                      value={minimumPrice}
                      onChange={e => setMinimumPrice(e.target.value)}
                      style={{ backgroundColor: "transparent !important" }}
                      required
                    />
                    <label htmlFor="email">Prix minimum</label>
                  </div>
                </div>
                <div className="row">
                  <div className="input-field col s12">
                    <input
                      id="maximum-price"
                      type="number"
                      name="maximumPrice"
                      placeholder="Entrez votre prix maximum"
                      value={maximumPrice}
                      onChange={e => setMaximumPrice(e.target.value)}
                      style={{ backgroundColor: "transparent !important" }}
                      required
                    />
                    <label htmlFor="email">Prix maximum</label>
                  </div>
                </div>
                <div className="row">
                  <div className="col s12" style={{ textAlign: "center" }}>
                    <button
                      className="btn waves-effect waves-light"
                      type="submit"
                      name="action"
                    >
                      Rechercher
                      <i className="material-icons right">send</i>
                    </button>
                  </div>
                </div>
              </form>

快递代码:

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


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

app.get("/info", (req, res) => {
  console.log("body ", req.body); <---------- ALWAYS AN EMPTY OBJECT
}

1 个答案:

答案 0 :(得分:2)

您正在使用axios进行获取请求。与get请求一起发送的参数在req.query中可用。

发布请求传递的参数在请求正文中接收。