I want to redirect to different pages based on some condition


when i run this code i get redirect to postUser page when i want to redirect if condition is true and render view if condition is false...

<pre class="lang-js prettyprint-override">router.get('/postedUser/:id', ensureAuthenticated, function(req, res) { User.findOne({_id: req.params.id}, function(err, data) { if (err) throw err; if (req.user._id == data._id) { res.redirect('/users/profile'); } else { res.render('postedUser', { data: data }); } }); });

can some one tell me where am going wrong..


You can not do so if you are submitting request using an API call from Ajax or other methods.

As all these methods are to implement <strong>Single Page Application</strong>, so rendering a different page is not allowed.

What happens when condition is met and request to render a different page?

The module who called API is waiting for response on browser to get some response from API, however your API is trying to load a different HTML page which browser prohibits and thus you will never get rendered via Ajax call.

How to do it?

There are two way out:

<ol><li>Single Page Application: Using JavaScript Frameworks like AngularJs, ReactJs will help you out by just changing HTML templates and not whole page.</li> </ol>

With Ajax you can do this:


<body> <div> <div align="center"> <form id="form1"> <label>Please enter below details</label><br><br> <label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br> <label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br> <label>Email Address *: </label><input type="email" name="email"><br><br> <br><br> <input type="button" value="Submit" onClick:"submitForm()"/> </form> <div id="showValue"></div> </div> </div> </body>


function submitForm() { $.ajax({ url: '/addName', type: 'POST', headers: headers, data: { "Fname": $("#FName").val(), "Lname": $("#LName").val(), "email": $("#email").val() }, success: function(result) { //append result to your html //Dynamic view $("#form1").hide(); var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>'; $("#showValue").html(html); }, error: function (error) { alert('error ',error); } }); }

Server side code I'm assuming you are using express.js and body-parser

app.post('/addName', (req, res) => { //Insert into db var body = req.body; res.send({ fName: body.FName, lName: body.LName }); }); <ol start="2"><li>Use form Submit method: using this you will be able to render the page however you can't send response back to same page i.e.,</li> </ol>


<body> <div> <div align="center"> //Can't send params using this approach //Data will be send as query string <form action="/postedUser/" method="GET"> <label>Please enter below details</label><br><br> <label>ID *: </label><input id="ID" type="text" name="ID"/><br><br> <input type="submit" value="Submit" /></form> </div> </div> </body>


//If there will be res.send({}); // This won't be returned to same page. But your code doesn't do any such thing router.get('/postedUser/', ensureAuthenticated, function(req, res) { User.findOne({_id: req.query.id}, function(err, data) { if (err) throw err; if (req.user._id == data._id) { res.redirect('/users/profile'); } else { res.render('postedUser', { data: data }); } }); });


  • iTunes Store operation failed. You must supply a CFBundleIdentifier for this request
  • When does HttpUrlConnection.usingProxy() return true?
  • Sql - SELECT rows until the sum of a row is a certain value
  • boost fusion: strange problem depending on number of elements on a vector
  • Forcing a context switch from the userland on Linux?
  • How to read data from socket connection - android
  • javafx 3d performance large data set
  • Error building image: Error building rlang - not available on R 3.5.0 (Uploading shiny)
  • Read a file in “chunks” using PHP
  • Leaflet z-index
  • Rails 5 - Google Maps - Javascript error - initMap is not a function - fixing one js issue creates a
  • auth.provider is not set to 'password' when user signs-in with email and password
  • How can I extend PHP DOMElement?
  • Google OAuth: can't get refresh token with authorization code
  • How to render a pixel array most efficiently to a window in c++?
  • what makes a request a new request in asp.net C#
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Adjust width of select element according to selected option's width
  • System.InvalidCastException: Specified cast is not valid
  • How do I exclude a dependency in provided scope when running in Maven test scope?
  • Is there a perl module to validate passwords stored in “{crypt}hashedpassword” “{ssha}hashedpassword
  • With Hadoop, can I create a tasktracker on a machine that isn't running a datanode?
  • Django rest serializer Breaks when data exists
  • Meteor helpers not available in Angular template
  • Read a local file using javascript
  • Display issues when we change from one jquery mobile page to another in firefox
  • swift auto completion not working in Xcode6-Beta
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • Why winpcap requires both .lib and .dll to run?
  • Is there a mandatory requirement to switch app.yaml?
  • Cannot Parse HTML Data Using Android / JSOUP
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • AngularJs get employee from factory
  • C# - Getting references of reference
  • using HTMLImports.whenReady not working in chrome
  • How to set the response of a form post action to a iframe source?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • unknown Exception android