【发布时间】: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