React + Express:代理错误:无法从localhstem_errors代理请求/总计

时间:2018-10-04 19:05:34

标签: javascript node.js reactjs express

这是我上一个问题的后续问题 React.js: Axois Post stay on pending(but i am getting data)

我的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"
}

我的server.js:

const express = require('express');
const app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());


//DB connections
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";

// console.log that your server is up and running
app.listen(3001, () => console.log(`Listening on port 3001`));


// create a GET route
app.get('/test', (req, res) => {
  var data;
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    var query = { address: "Highway 37" };
    dbo.collection("customers").find(query).toArray(function(err, result) {
      if (err) throw err;
      data = result
      res.send(data[0])
      db.close();
    });
  });
});

//A Get route for getting personal Cart information
app.get('/myCart', (req, res) => {
  var total = 0;
  var data = []

  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("cart");
    dbo.collection("items").find().toArray(function(err, result) {
      if (err) throw err;

      var obj = []
      if(result.length >0){
        for(var i = 0; i < result.length; i++ ){
          var description = result[i].desc;
          var price = result[i].price
          if (!obj[description]) { // Add new object to result
            obj[description] = {
                desc: description,
                total: price,
                amount: 1
            };
          }else{
            obj[description].total += price
            obj[description].amount +=1
          }
        }

        for(var key in obj){
          console.log(obj[key])
          data.push(obj[key])
          total += obj[key].total
        }
      }

      res.send({express: data})
      db.close();
    });
  });



}); 


//a Post route for posting the added item to the data base
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.sendStatus(200)
      console.log("Number of documents inserted: " + result.insertedCount);
      db.close()
    });
  });
});


app.get('/wallet', (req, res) => {
  var data;
  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("wallet");
    dbo.collection("account").findOne({}, function(err, result) {
      if (err) throw err;
      res.send( {express: result.amount})
      db.close();
    });
  });


});

app.get('/total', (req, res) => {
  var total = 0;

  MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("cart");
    dbo.collection("items").find().toArray(function(err, result) {
      if (err) throw err;
      for(let item of result){
        total += item.price;
      }
      res.send({express: total})
      db.close();
    });
  });
});

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);
      res.sendStatus(200)
      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);
      res.sendStatus(200)
      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);
      res.sendStatus(200)
      console.log("Numer of record deleted " + res.deletedCount)
      db.close();
    })
  })
})

问题在于,在将res.send()添加到我的代码中之后,由于代理错误,现在我的路由全部中断了:无法代理localhstem_errors的请求/总计。这个问题以前发生过。实际上,自从我创建我的react + express应用以来,这一直是一个警告,但这只是一个警告,似乎并没有影响我的应用,但是现在确实如此。另外,也是导致问题的原因是发布路线中的res.send()。在这些获取路由器中,res.send()很好

对此有任何解决办法吗?我觉得这不会是一个小问题。我可以重新启动我的项目吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试在package.json中设置代理吗?

"proxy": {
    "/*":  {
        "target": "http://localhost:3001"
    }
}

关于以下错误,res.sendStatus应该置于mongo连接之外

  

发送后无法设置标题

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() 
   }); 
}); 
   res.sendStatus(200) 
});