React.js:Axois Post待处理(但是我正在获取数据)

时间:2018-10-04 18:01:55

标签: node.js reactjs axios

我正在使用axios对Node.js执行发布请求。数据确实到达了后端,我可以对其执行一些操作。但是,在网络中,它始终保持未决状态。

以下是示例路由器:

  handleSubmit(e){
    e.preventDefault();
    var added = this.getAddedItems()

    console.log("added is", added)
    if(added.length > 0){
      for(let i of added){
        console.log(i)
      }

      axios({ method: 'post', url: '/add', data: added})
    }
  }

handleDelete(e,desc){
        e.preventDefault()
        axios({method: "post", url: "/remove", data:{name: desc}})

    var newTotal = 0;

    var newArray = this.state.testData.filter(function(obj){
        return obj.desc !== desc
    })

    newArray.map(item => (
        newTotal += item.total
    ))

    console.log(newTotal)
    this.setState({ 
        testData: newArray,
        total: newTotal
    })
}

   handleSubmit(e){
        e.preventDefault()
        var remain = this.state.wallet - this.state.total

        this.setState({
            buyAttempt: true,
        })

        console.log("remain is " + remain)
        console.log("length " + this.state.testData.length)
        if(remain >= 0 && this.state.testData.length > 0){
            this.setState({buySuccessful: true})
            axios({ method: 'post', url: '/buy', data: { amount : remain}})



            this.setState({
                wallet:remain,
                testData: [],
                //itemNum:0
            })
        }
    }

这些是我组件中的方法。他们都执行后请求。后端实际上正在接收数据,所以我没有注意到它。但是,最近我的应用程序坏了,我怀疑这是因为永无休止的等待中。

我也收到错误消息,该消息实际上会破坏我的应用程序

POST http://localhost:3000/add net::ERR_EMPTY_RESPONSE
Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)

POST http://localhost:3000/buynet::ERR_EMPTY_RESPONSE
Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)

POST http://localhost:3000/remove net::ERR_EMPTY_RESPONSE
Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87) 

我需要帮助的地方: 1:如何解决此问题 2:是否有更好的替代方法(反应的自然方式来执行发布请求)

我的server.js

app.post('/buy', (req, res) => {
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) console.log(err);
    var dbo = db.db("wallet");
    var myquery = { amount: {$gt: 0} }
    var newquery = { $set: {amount: req.body.amount}}
    dbo.collection("account").updateOne(myquery, newquery, function(err, re) {
      if (err) console.log(err);
      console.log("Wallet updated:", req.body.amount )
      db.close();
    });
  });


  MongoClient.connect(url, { useNewUrlParser: true}, function(err, db) {
    if (err) console.log(err);
    var dbo = db.db("cart");
    dbo.collection("items").deleteMany({}, function(err, res){
      if (err) console.log(err);
      console.log("numer of data deleted " + res.deletedCount)
      db.close();
    });
  });


});

app.post('/remove', (req,res) => {
  MongoClient.connect(url, { useNewUrlParser: true}, function(err,db){
    if (err) console.log(err);
    var dbo = db.db("cart");
    var myquery = { desc: req.body.name}
    console.log(req.body.name)
    dbo.collection("items").deleteMany(myquery, function(err,res){
      if(err) console.log(err);
      console.log("Numer of record deleted " + res.deletedCount)
      db.close();
    })
  })
})

app.post('/add', (req, res) => {
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("cart");
    var objs = req.body;
    dbo.collection("items").insertMany(objs, function(err, result) {
      if (err) console.log(err);
      console.log("Number of documents inserted: " + result.insertedCount);
      db.close()
    });
  });
});

Package.json:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "bootstrap": "^4.1.3",
    "express": "^4.16.3",
    "mongodb": "^3.1.6",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-html-parser": "^2.0.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "1.1.5",
    "reactstrap": "^6.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:3001"
}

1 个答案:

答案 0 :(得分:1)

问题是您没有在api调用中发送回购邮件。您需要像下面提到的那样在每个api调用中发送响应

app.post('/buy', (req, res) => {
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) console.log(err);
    var dbo = db.db("wallet");
    var myquery = { amount: {$gt: 0} }
    var newquery = { $set: {amount: req.body.amount}}
    dbo.collection("account").updateOne(myquery, newquery, function(err, result) {
      if (err) console.log(err);
      res.send("Wallet updated);
      //if you want to send in json format then
      res.json({"message": "Wallet updated", "result": result});
      console.log("Wallet updated:", req.body.amount )
      db.close();
    });
  });


  MongoClient.connect(url, { useNewUrlParser: true}, function(err, db) {
    if (err) console.log(err);
    var dbo = db.db("cart");
    dbo.collection("items").deleteMany({}, function(err, result){
      if (err) console.log(err);
      res.send("numer of data deleted " + result.deletedCount)
      db.close();
    });
  });


});

app.post('/remove', (req,res) => {
  MongoClient.connect(url, { useNewUrlParser: true}, function(err,db){
    if (err) console.log(err);
    var dbo = db.db("cart");
    var myquery = { desc: req.body.name}
    console.log(req.body.name)
    dbo.collection("items").deleteMany(myquery, function(err,result){
      if(err) console.log(err);
      res.send("Numer of record deleted " + result.deletedCount)
      db.close();
    })
  })
})

app.post('/add', (req, res) => {
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("cart");
    var objs = req.body;
    dbo.collection("items").insertMany(objs, function(err, result) {
      if (err) console.log(err);
      res.send("Number of documents inserted: " + result.insertedCount);
      db.close()
    });
  });
});

此外,在每个api调用中,您都有两次res,因此请更改一个res作为结果或您选择的任何名称。因为节点会混淆两个资源。因此,我已更改res以导致每次api调用。