React + Express:代理错误:无法从localhstem_errors代理请求/总计 [英] React + Express: Proxy error: Could not proxy request /total from localhstem_errors

查看:43
本文介绍了React + Express:代理错误:无法从localhstem_errors代理请求/总计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我上一个问题的后续问题反应.js:Axois Post待处理(但我正在获取数据)

This is a follow-up question from my previous question React.js: Axois Post stay on pending(but i am getting data)

我的package.json文件

My package.json file

{
  "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:

My 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()很好

The problem is that after adding res.send() to my code, now my route are all broken because of the Proxy error: Could not proxy request /total from localhstem_errors. This problem happened before. Actually it has been a warning since I created my react+express app, but it was just a warning and does not seem to affect my app, but now it does. Also, it is the res.send() in the post route that is causing the problem. In these get routers, res.send() was fine

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

Any fix to this? I feel like it is not going to be a trivial fix. May I have to restart my project?

推荐答案

是否可以尝试在package.json中设置代理,如

Can you try setting your proxy in package.json like

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

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

Regarding below error the res.sendStatus should be placed out of mongo connection

发送后无法设置标题

Can't set headers after they are sent

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) 
});

这篇关于React + Express:代理错误:无法从localhstem_errors代理请求/总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆