【问题标题】:MEAN stack update view with Node/Express response带有 Node/Express 响应的 MEAN 堆栈更新视图
【发布时间】:2017-01-11 19:08:49
【问题描述】:

我有一个 MEAN 堆栈仪表板应用程序 (server1) 与 nodejs/express 服务器 (server2) 通信,该服务器对 mongoDB 进行查询。例如,用户应该通过仪表板应用程序日历选择一个月,该日期将被发送到 nodejs/express 服务器,该服务器将查询 mongo 并返回例如您在该月去健身房的次数。

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

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

仪表板应用程序 - 角度前端

$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 堆栈,所以我意识到这听起来像是一个基本问题,但我真的被困住了。

【问题讨论】:

  • 您也可以随时使用 Postman 检查您的路线。

标签: angularjs node.js mongodb express mean-stack


【解决方案1】:

尽管您已将 promise 链接起来,但您的顺序会有所不同,因为您没有返回 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);
});

或者任何想法,如果可能的话,我可以将 /getQueryJson 的响应直接发送到前端控制器,而无需向 /sendToController 发出另一个请求?

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多