具有 Node/Express 响应的 MEAN 堆栈更新视图

MEAN stack update view with Node/Express response

我有一个 MEAN 堆栈仪表板应用程序 (server1) 与 nodejs/express 服务器 (server2) 通信,这使得查询 mongo 数据库。例如,用户应该通过仪表板应用程序日历 select 一个月,这个日期将被发送到 nodejs/express 服务器,该服务器将查询 mongo 和 return 例如那个月你去健身房的次数。

我得到了正确的响应,但我在更新视图时遇到了问题(因为 http 请求是异步的,响应中的请求执行得更快,因此用错误的值更新了我的视图)

我按如下方式处理了我的请求:

仪表板应用程序 - angular 前端

$scope.query = function () {
        console.log("I am hereee");
        var month = ("0" + ($scope.dt.getMonth() + 1)).slice(-2);
        var date = $scope.dt.getFullYear() + "" + month;
        var queryData = JSON.stringify({MemberID_Hash: $scope.memberNo, Date_Key_Month: date});
        console.log("data: ", queryData);
        console.log("url: ", expressQuery);
        $http({ //send query to node/express server
            method: 'POST',
            url: expressQuery,
            data: queryData,
            withCredentials: true,
            headers: {
                    'Content-Type': 'application/json; charset=utf-8'
            }
        }).then(function(response) { //read backend response
            console.log (">>>>>>>>");
            $http({
            method : "POST",
            url : "http://localhost:9000/sendToController"
            }).then(function mySucces(response) {
              console.log("responde.data: ", response.data);
              $scope.nrOfSwipes = response.data;
            }, function myError(response) { });
        });
    };  

仪表板应用程序 - express 后端

var dataController = "test"; // used a global variable to save the response value to update my view (bad design => thus, any help/suggestions would be greatly appreciated)

module.exports = function(app) {

    // receives the response from server2 - !! this is executed 2nd
    app.post('/getQueryJson', function(request, response) {
        if(response.statusCode == 200) { 

          console.log("In routes.js TESTING......")
          console.log("This is your request: ", request.body);

          dataController = request.body;
          console.log("dataController1: ", dataController);
          response.send(request.body);
        }else{
          response.send(" Error code: " + response.statusCode);
        }
    });

    // updates the view - !! this is executed first
    app.post('/sendToController', function(request, response) {
        console.log("dataController2: ", dataController);
        response.send(dataController);
    });
};

问题是请求需要更长的时间来处理,所以我调用 sendToController 的响应首先执行,然后 getQueryJson。 知道如何改变它们的执行方式吗?或者任何想法,如果可能的话,我可以将 /getQueryJson 的响应直接发送到前端控制器,而不必向 /sendToController 发出另一个请求?

我刚开始接触 MEAN 堆栈,所以我意识到这听起来像是一个基本问题,但我真的被卡住了。

虽然您已经链接了承诺,但您的顺序不同,因为您没有返回 Promise。编辑您的代码以执行命令。

$http({
  method: 'POST',
  url: expressQuery,
  data: queryData,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
}).then(() => {
  return $http({
    method: 'POST',  //read backend response
    url: 'http://localhost:9000/sendToController'
  });
}).then((response) => {
  console.log(`responde.data: ${response.data}`);
  $scope.nrOfSwipes = response.data;
}).catch((err) => {
  //if error occurs
  console.log('err', err.stack);
});

进一步检查您的代码,我发现调用 sendToController 不会从 getQueryJson 获取任何输入。如果真是这样的话。您可以在上面使用 Promise.all()

对您的代码进行此更改。

Promise.all([
  $http({
    method: 'POST',
    url: expressQuery,
    data: queryData,
    withCredentials: true,
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }
  }),
  $http({
    method: 'POST',  //read backend response
    url: 'http://localhost:9000/sendToController'
  })
]).then((responses)=> {
  let ctrlResponse = responses[1];
  console.log(`responde.data: ${ctrlResponse.data}`);
  $scope.nrOfSwipes = ctrlResponse.data;
}).catch((err) => {
  console.log('err', err.stack);
});

or any idea if it possible I can send the response from /getQueryJson directly to the frontend controller without having to make another request to /sendToController?

是的。我们能做到这一点。您需要使用 json 中的对象进行响应。但是您提供给我们的代码似乎是占位符。如果你能合并它们。它可能看起来像

response.status(200).send({
    query: 'some string', // your getQueryJson response,
    controller: 'some more value' //sendToController
});