Search code examples
javascriptnode.jsexpresstemplate-engine

href link between two webpages on server in node.js with express package and EJS template engine


I have a server_render.js as follows. I have used express package of NPM. I have tow webpages in views directory, one is home.ejs and the other is portal.ejs. I used the EJS template engine.

var express=require('express')
var app=express()
const port=process.env.PORT || 10002

//app.use(express.static(__dirname+'/public'))

//template engine
app.set('view engine','ejs');

//homepage
app.get('/',function(req,res){
    res.render('home.ejs');
})
//signin page: 127.0.0.1:10002/signin
app.get('/signin',function(req,res){
    res.render('portal.ejs');
});

//run nodejs loop server
app.listen(port,function(err){
    if(err){
        throw err
    }
    console.log('server is listening on '+port+' ...')
})

views/home.ejs looks like this:

<!DOCTYPE html>
<html lang='en'>
<head>
    <title>Portal</title>
</head>
<body>
<div>You need to <a href='portal.ejs'>sign-in</a></div>
</body>
</html>

and views/portal.ejs is this:

<!DOCTYPE html>
<html lang='en'>
<head>
    <title>Portal</title>
</head>
<body>
<input name="username" id="username" type="text" placeholder="username"></input>
<input name="password" id="password" type="text" placeholder="password"></input>
</body>
</html>

I want to create a link from home.ejs to portal.ejs. I tried href="portal.ejs" however it did'nt work. I wonder what's the method.


Solution

  • You can't link to the actual ejs files. In your code you have declared the following paths:

        //homepage
    app.get('/',function(req,res){
        res.render('home.ejs');
    })
    //signin page: 127.0.0.1:10002/signin
    app.get('/signin',function(req,res){
        res.render('portal.ejs');
    });
    

    This means that your express app has urls at '/' and '/signin'. On each of those two paths you have declared to render either home.ejs or portal.ejs as the output HTML.

    Just point the links to '/' and '/signin' instead of the actual template files.