我有一个设置页面,您可以在其中插入和删除一些过滤器。对于删除请求,我使用了这个:
$('#delete-filter').click(function (e) {
var filtername = $('#filter-list').val();
var filterCount = $('#filter-list option').length;
var retVal = confirm("Are you sure to delete this filter?");
if( retVal == true ){
$.ajax({
url: "/settings?filtername=" + filtername,
method: 'DELETE',
dataType: "json",
success: function (result) {
}
});
}
else{
return false;
}
});
这是我的页面路径:
router.delete('/settings', ensureAuthenticated, function (req, res, next) {
var promise = user.deleteFilter(req.session.user_id, req.query.filtername);
var promise2 = promise.then(function (data) {
req.session.selected_filter = data.selected;
res.redirect('/settings');
}, function (error) {
console.log(error);
})
})
本质上,我想重定向到设置页面,以便页面重新加载新数据。但是在 promise 链中我不能使用任何响应函数。我使用重定向错误吗?或者我无法在 promise 链中发送响应?
最佳答案
您错误地识别了问题。
当您发出 HTTP 重定向时,您会说“您正在寻找的东西?改为从这里获取它。”
这与“浏览器应将此 URL 显示为新页面”不同。
紧随其后的是 HTTP 重定向,设置页面被传送到浏览器,然后浏览器将其作为成功函数中的 result
提供。 (然后您完全忽略它,因为您没有在该函数中放入任何东西)。
如果您希望浏览器加载新页面,则需要将 URL 作为数据(而不是重定向)传递,然后将该值分配给 location.href
.
设置页面可能不应该动态确定,因此您可以将 URL 硬编码到成功函数中。
硬编码会更有意义,因为您不应该发送重定向来响应 DELETE request :
If a DELETE method is successfully applied, the origin server SHOULD send a 202 (Accepted) status code if the action will likely succeed but has not yet been enacted, a 204 (No Content) status code if the action has been enacted and no further information is to be supplied, or a 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.
关于javascript - Node.Js promise 重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45735281/