我很抱歉,如果這是一個愚蠢的問題,請允許我解釋一下。我正在運行一個MEAN應用程序。angularjs - 我可以有兩個.post請求解析爲相同的API端點嗎?
在我的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文檔中。
當我一次運行一個函數時,每個單獨的函數都能夠成功工作,並將其推入正確的數組中。 但是,當我同時在同一頁面上運行include兩個函數時,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中調用query2返回的promise。 – user2263572
如果您使用的是RESTful API,那麼不需要。您應該以不同方式表示資源,以免遇到此問題。這更多的是設計問題。 – jmugz3
@ user2263572感謝您的建議,我現在嘗試使用我的api端點或嘗試一個有條件的請求。 – amyloula