首页 > 解决方案 > React - 获取请求未在正文中发送内容

问题描述

我没有从fetch服务器端的请求中获取正文对象中的数据。我已经在 SO 上尝试过其他解决方案,但到目前为止,我的情况没有任何效果。我在后端使用 Node express,在前端使用 React。

在组件中:

addCity = _ => {
    const { city } = this.state;
    fetch('http://localhost:3003/city_create', {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        create_name: city.name,
        create_district: city.district,
        create_population: city.population
      })
    })
      .then(res => {
        console.log(res);
        this.getCities;
      })
      .catch(err => console.log(err))

  }

服务器路由:

router.post('/city_create', (req, res) => {
    console.log("Trying to create new city...")
    const { create_name, create_district, create_population } = req.body;
    //debugger
    const queryString = "INSERT INTO city (Name, District, Population, CountryCode) VALUES (?,?,?,'PAK')";

    getConnection().query(queryString, [create_name, create_district, create_population], (err, rows, fields) => {
        console.log(create_name, create_district, create_population);
        if (err) {
            console.log('A db error occurred:' + err);
            res.sendStatus(500);
            return;
            //throw err;
        }
        console.log("Inserted a new City with Id: ", rows.insertId);
    });

    res.end();
});

也尝试在标题中使用FormData和属性,但没有运气。accept

标签: node.jsreactjsexpressfetch

解决方案


您需要安装body-parser模块以提取传入请求流的整个正文部分并将其公开在 req.body 上。

之前是express的一部分,现在需要单独安装。

npm install body-parser --save

并将中间件用作:

app.use(bodyParser.json())


推荐阅读