Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current url path in express with ejs

Tags:

node.js

I want to search browser a query in Nodejs for How can I get current page URL Express with Ejs

like image 302
Deepak Kumar Avatar asked Mar 22 '17 05:03

Deepak Kumar


2 Answers

The protocol is available as req.protocol. docs here

var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

By using above example, you can get full page URL.

like image 132
Bhaurao Birajdar Avatar answered Sep 29 '22 15:09

Bhaurao Birajdar


Bhaurao's answer is good - but to give Deepak his full request (make the path available in EJS), you can do the following:

In your application code where you initialise Express:

let app=express();
app.use ((req, res, next) => {
    res.locals.url = req.originalUrl;
    res.locals.host = req.get('host');
    res.locals.protocol = req.protocol;
    next();
});

Now, in your EJS, you should have access to the variables url, host and protocol. For example: <%= url %> will print the URL.

Hope that helps.

like image 22
DanJHill Avatar answered Sep 29 '22 14:09

DanJHill