Res.send (), then res.redirect ()

Why does the following not work?

res.send({ successMessage: 'Task saved successfully.' }); res.redirect('/'); 

I basically need the successMessage command for AJAX requests. Forwarding is required when the request is a standard mail request (not AJAX).

The following approach does not seem to me very clean, since I do not want to care about the interface technology in my backend:

 if(req.xhr) { res.contentType('json'); res.send({ successMessage: 'Aufgabe erfolgreich gespeichert.' }); } else { res.redirect('/'); } 
+7
express
source share
2 answers

You can use the status code to indicate that your task has been saved and then redirected. Try the following:

 res.status(200); res.redirect('/'); 

OR

 res.redirect(200, '/'); 

Since AJAX knows success or failure codes, for example, if you send 404, the AJAX success function will not execute

+3
source share

The first fragment does not work, because res.send sends headers already, so res.redirect after that is simply impossible.

The second fragment should work. Basically, it is checking if the AJAX request (then returns JSON), otherwise a redirect occurs.

+1
source share

All Articles