简体   繁体   中英

Node.Js promise redirect doesn't work

I have a settings page that you can insert and delete some filters. For delete request I used this:

$('#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;
           }

    });

And here is my route for this page:

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);
    })
})

Essentially I want to redirect to page to settings, so the page reloads with the new data. But in promise chain I can't use any response functions. Am I using the redirect wrong? or I can't send a response in promise chain ?

You've misidentified the problem.

When you issue an HTTP redirect, you say "The thing you were looking for? Get it from here instead."

This is not the same as "The browser should display this URL as a new page".

The HTTP redirect is followed, the settings page is delivered to the browser, then the browser makes it available as the result in your success function. (You then completely ignore it as you haven't put anything in that function).

If you want the browser to load a new page, then you need to deliver the URL as data (not as a redirect) and then assign that value to location.href .

The settings page probably shouldn't be determined dynamically, so you can probably just hard code the URL into the success function.

Hard coding it would make more sense, since you shouldn't send a redirect in response to a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM