【问题标题】:React - Fetch request not sending content in bodyReact - 获取请求未在正文中发送内容
【发布时间】:2018-08-20 19:01:51
【问题描述】:

我没有从服务器端的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();
});

尝试在标头中使用 FormDataaccept 属性,但没有成功。

【问题讨论】:

  • 你在 node.js 中使用过body-parser 吗?

标签: node.js reactjs express fetch


【解决方案1】:

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

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

npm install body-parser --save

并将中间件用作:

app.use(bodyParser.json())

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 2015-11-08
  • 2015-04-12
  • 1970-01-01
相关资源
最近更新 更多