【发布时间】:2016-08-15 03:17:10
【问题描述】:
如果这是一个愚蠢的问题,我深表歉意,请允许我稍微解释一下。我正在运行一个 MEAN 应用程序。
在我的 CRUD 生成模块的服务器路由中,我已将 两个单独的发布请求包含到同一个 api 端点。
app.route('/api/tasks/:taskId').all(tasksPolicy.isAllowed)
.get(tasks.read)
.put(tasks.update)
.delete(tasks.delete)
.post(tasks.newCo)
.post(tasks.newOffer);
其中每一个都根据 taskId 向我的 mongo 文档执行单独的推送请求。
当我一次运行一个函数时,每个单独的函数都会成功运行并推送到正确的数组中。 但是,当我同时在同一页面上运行包含两个函数时,newOffer 函数会将一个空值推送到 newCo 数组中。并且 newCo 函数继续成功运行。
我不知道为什么..
再次,如果这是一个愚蠢的问题,我深表歉意。
server.controller.js
/**
* Add a new comment
*/
exports.newCo = function(req, res) {
Task.findOneAndUpdate({_id: req.params.taskId},
{
"$push": {
comments: req.body.comment
}
}, {
new: true //to return updated document
})
.exec(function(error, task) {
if (error) {
return res.status(400).send({message: 'Failed to add comment due to invalid params!'});
}
return res.status(200).send(task);
});
};
/**
* Add a new offer
*/
exports.newOffer = function(req, res) {
Task.findOneAndUpdate({_id: req.params.taskId},
{
"$push": {
offers: req.body.offer
}
}, {
new: true //to return updated document
})
.exec(function(error, task) {
if (error) {
return res.status(400).send({message: 'Failed to add offer due to invalid params!'});
}
return res.status(200).send(task);
});
};
client.controller.js
vm.newCo = function() {
$http.post('/api/tasks/' + task._id , {comment: { comment: vm.task.newComment, user: vm.authentication.user, profileImageURL: vm.authentication.user.profileImageURL, displayName: vm.authentication.user.displayName } })
.then(successCallback, errorCallback);
function successCallback(res) {
$state.transitionTo($state.current, $state.params, {
reload: true,
inherit: false,
notify: true
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
};
//close new comment function
//new offer
vm.newOffer = function() {
$http.post('/api/tasks/' + task._id , {offer: { offerDesc: vm.task.offerDesc, offerPrice: vm.task.offerPrice, user: vm.authentication.user, profileImageURL: vm.authentication.user.profileImageURL, displayName: vm.authentication.user.displayName } })
.then(successCallback, errorCallback);
alert('it worked!');
function successCallback(res) {
$state.transitionTo($state.current, $state.params, {
reload: true,
inherit: false,
notify: true
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
};
//close new offer function
【问题讨论】:
-
我看到了两种可能的解决方案。 1. 建立一个端点并在需要时让它运行多个查询(可以基于请求对象有条件)。然后让那个端点返回响应。 2. 从客户端进行第一次查询,在该查询的响应表单上,向后端进行第二次查询并将查询 1 所需的数据传递。您需要做的就是从 query1 返回的 promise 中调用 query2。
-
如果您使用的是 RESTful api,那么不。您应该以不同的方式表示您的资源,这样您就不会遇到这个问题。这更像是一个设计问题。
-
@user2263572 感谢您的建议,我现在将尝试弄乱我的 api 端点或尝试条件请求。
-
@jmugz3 谢谢你的澄清
标签: angularjs mean-stack