代码之家  ›  专栏  ›  技术社区  ›  Abdul Rafay

React-获取请求不在正文中发送内容

  •  0
  • Abdul Rafay  · 技术社区  · 7 年前

    我没有从body对象中获取数据 fetch 在我的服务器端请求。我已经尝试了其他的解决方法,但到目前为止,我的情况还没有任何效果。我在后端使用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 标题中也有属性,但没有运气。

    1 回复  |  直到 7 年前
        1
  •  1
  •   McRist    7 年前

    你需要安装 body-parser

    它以前是express的一部分,现在我们需要单独安装。

    npm install body-parser --save

    app.use(bodyParser.json())

    推荐文章