简体   繁体   中英

Changing view in express using Jade

I'm pretty new to the node scene, i'm using express with jade and i've managed to get a simple 1 page app working. Currently a login page is served as the default page, Once the user is authenticated against a database a function loginUser() is called.

What I would like to do is change my view once this function is entered, Iv'e tried several ways but no luck so far.

Here is how my initial view is rendered when server 1st starts

var express = require("express");
var app = express();
var port = 3700;

app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");

app.engine('jade', require('jade').__express);

// Page 1
app.get("/", function (req, res) {
    res.render("page");
});

// Page 2 (Once logged in)
app.get('/newpage', function (req, res) {
    res.render('mainpage', {
        title: 'Home'
    });
});

app.get("/", function (req, res) {
    res.send("It works!");
});
app.use(express.static(__dirname + '/public'));

Any information on how to get my second view "/newpage" to show once a certain function is called in my index.js would be greatly appreciated

Thanks!

Your app.get('/newpage', function (req, res) function tells Express that when there is a GET HTTP request for yourwebsite.com/newpage then it will render the mainpage with a title of Home . That looks correct so far.

To answer your question, you just need to make the clientside login button be a link to this /newpage if the login information is correct (I'm guessing if loginUser() is successful). Otherwise, either go back to the home page '/' or display a your password was incorrect either as a page, or on the same home page.

You may handle this logic in your Express server, as a PUT or POST request sending in their login info with app.post() or app.put() . You can also add some form of authentication in your GET ( app.get() ) requests' header, just to make sure that the client is really who they say they are. You can see the details of the responses and requests if you print out parts of your response or request objects in express. Express is neat in that you can also add functions when a certain request goes to a certain route, like say, to count the number of requests you get, or for debugging purposes.

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