Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper usage of res.render() and res.redirect() in Express?

I'm having some trouble deciphering the ambiguity between

res.render('viewname', {msg: 'Message' }) 

and

res.redirect('route')

The redirect function does not let you pass a "message", but you may still want to, and the render function will render your view, but it will not change the URL of your web app and will not trigger the function which is required for your route.

The situation I am having is that I have an Invite form, which has an action that changes my URL, and triggers a function at that route which has a success and failure callback, and I would like to redirect users to the Dashboard with a message indicating success or failure.

like image 473
netpoetica Avatar asked Dec 10 '12 04:12

netpoetica


People also ask

What does res render () function do?

The res. render() function is used to render a view and sends the rendered HTML string to the client.

What is the difference between render and redirect in node JS?

-Redirect is a method that is used to issue the error message in case the page is not found or it issues a 302 to the browser. Whereas, render is a method used to create the content. -Redirect is used to tell the browser to issue a new request.

How do you Res send and 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 render in Express?

render() method is used for returning the rendered HTML of a view using the callback function. This method accepts an optional parameter that is an object which contains the local variables for the view.


1 Answers

look at connect-flash to use rails style flashing of messages.

res.render() will render the view with data passed to it, res.redirect() will redirect a user to another page (at which point the request starts over)

like image 132
chovy Avatar answered Sep 29 '22 11:09

chovy