Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why is the following not working?

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

I basically need the successMessage for AJAX requests. The redirect is necessary when the request is a standard post request (non-AJAX).

The following approach doesn't seem to be very clean to me as I don't want to care about the frontend-technology in my backend:

if(req.xhr) {
    res.contentType('json');
    res.send({
        successMessage: 'Aufgabe erfolgreich gespeichert.'
    });
} else {
    res.redirect('/');
}
like image 803
mosquito87 Avatar asked Jan 29 '14 18:01

mosquito87


People also ask

How do I Res redirect?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below. const app = require('express')(); // The `res.

What is difference between RES redirect and res render?

In the specific case you show in your question, when you "approve" the login, you may then want to do a res. redirect() to whatever URL you want the user to start on after the login and then create a route for that URL which you will use res. render() to render that page.

What does Res send () do?

send() Send a string response in a format other than JSON (XML, CSV, plain text, etc.). This method is used in the underlying implementation of most of the other terminal response methods.


1 Answers

You can use a status code to indicate that your task was saved and then redirect. Try this:

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

OR

res.redirect(200, '/');

Because AJAX knows success or failure codes, so for example if you'll send 404, AJAX success function won't execute

like image 133
M Omayr Avatar answered Sep 22 '22 06:09

M Omayr