Pass Node env to layout.jade in Express without explicitly defining route - javascript

So, I get passing parameters to Jade files- piece of pie:
app.use('/myroute', function (req, res) {
res.render('myview', {somevar: 'Testing!'});
});
However- I have my layout.jade file that is implicitly read and rendered by Express, with no actual definition of route-view binding, and I'm trying to work out how to pass a variable into that template.
Any ideas? Cheers!
Ps- this is so that I can pass node's development/production variable to some front-end javascript that's being added on every page.

Ah, I worked out the answer. Set it as a local variable in express, as mentioned here: Express.js View "globals"
So, in app.js I included app.locals.env = app.settings.env; and then in my layout.jade I added my javascript and simply used #{env} inside the script to get the environment value.

You can also use #{settings.env} in the jade template, which get the value from app.locals.settings.env

Related

How to pass data from nodejs to inside html script tags

I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?
static-pages-server.js:
app.get('/index', function(req, res) {
var name = "hello";
res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
});
index.html:
<script type="text/javascript">
console.log(name);
</script>
Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.
<script type="text/javascript">
console.log(<%=name%>);
</script>
Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.
Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html
Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide data not to render HTML. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.
You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.
It would allow you to pass data directly from your routes into the page you are rendering.
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.
Simply modify your index.html like this:
<script type="text/javascript">
let name = "{{name}}";
console.log(name);
</script>
here is the answer How do I use HTML as the view engine in Express?
what you will need is a view engine package in your app. there are many view engines currently available.
then set that view engine in express app. Trigger the view render via a call from your route’s response like you have done above.
Then in your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.
check out esj or pug (ps pug is my personal favourite )

NodeJS Render parameter to local JS

I am looking for an information.
How to pass a variable from NodeJS res.render('index', { title: "Hey"}) to local JS.
I use express (with helmet) and PugJs. I can include my var in the template, but I want to store it on the JS file who's part of the template. (No inline script, vanilla JS)
Currently, I use a hidden Input in the template to store the data, the JS script get the input and do the work.
How I can pass the variable thought the template to my JS file?
Sorry, I 'm French :(
Thank you for your time!

How to render static file not in public or view folder after middlware in express js

I have a folder
api-docs inside that I have index.html some css and js file
I need to render api-doc for authenticated user.
I am not using it in views as In project I am using jade in view and api-doc is in html
I have tried
router.get('/v1/secure-api-documentation',(req,res)=>{
console.log('A')
res.sendFile(__dirname + '/../api-doc/index.html');
});
and
router.get('/v1/secure-api-documentation',ensureAuthenticate,(req,res)=>{
express.static(path.join(__dirname,'../api-doc'))
});
express.static(path, [options]) returns a function. So basically what your code is doing is :
router.get('/v1/secure-api-documentation',ensureAuthenticate,(req,res)=>{
express_static_function // this function further accepts arguments req, res, next
//there is no function call happening here, so this is basically useless
});
However, this is not what express.static is used for
What express.static does is, takes the request path and looks for a file with the same name in the folder you specified.
Basically, if a GET request comes to '/v1/secure-api-documentation', it will take the request path after '/v1/secure-api-documentation' and look for that inside api_docs folder.
Passing express.static to router.get() will call it for the very SPECIFIC path. This is important.
GET '/v1/secure-api-documentation/index.html' will fail. Because such a route is not handled.
What you need to do this is call express static for any path like '/v1/secure-api-documentation/*'.
For this you need to take the express app object, and write the following code:
//make sure to use the change the second argument of path.join based on the file where your express app object is in.
app.use('/v1/secure-api-documentation',express.static(path.join(__dirname,'../api-doc')));
This will now work for not only the index.html file but any js/css file inside api_docs that is requested.

bootstrappedUser - Jade or EJS to HTML

I've been doing some guide on Mean stack and I came to a point where I'm currently stuck.
Following this guide, I have created a simple authentication where I'm able to log in using Passport JS. Whatsoever, each time when page refreshes, the authentication gets restarted (client doesn't recognise it anymore).
Since this is suppose to happen in the guide and we are about to fix it, guide said the following.
1. Create a Jade file and insert this:
if !!bootstrappedUser
script.
window.bootstrappedUserObject = !{JSON.stringify(bootstrappedUser)}
I've tried this in my html file but it doesn't work:
<script type='text/javascript'>
if (bootstrappedUser != "undefined" ){
window.bootstrappedUserObject = JSON.stringify(bootstrappedUser);
}
</script>
Getting the error: Uncaught ReferenceError: bootstrappedUser is not defined
even though I have created the variable in my backend js file and assigned req.user to it.
I'm suppose to have this file included in my main layout (index.html). The problem is that I'm not using Jade as template engine but plain HTML and I don't know how to transform this code up there to work as simple HTML in my index.html.
It seams that this statement up here only initialise when user hits the login button. Does anyone have any idea or solution how to write the above code in plain HTML.
I browsed StackOverflow and found almost similar problems but not similar enough.
Thanks in advance,
Aleksandar
bootstrappedUser is a variable passed by server-side code to Jade compiler which injects it into the HTML while compiling. If you plan on writing the HTML yourself you can not inject variables from server-side code, obviously because HTML is just a static markup. You'll probably have to get that variable at the client-side from the server yourself via ajax or something.
Via Angular controller let's say ?
You can first define a route on server that serves the variable you want
app.get('/bootstrappedUser', function(req, res){
if(req.user)
res.json(req.user);
else
res.status(401).end();
});
Then on client-side angular you can perform an http request and get that variable
$http.get('/bootstrappedUser')
.success(function(data, status, headers, config) {
$scope.bootstrappedUser = data;
});

Node.js: Pass variables to a file

I am sending a .XML file using res.sendfile 'xml/foo.xml'. How can I pass variables to the foo.xml file and change the .XML content accordingly?
Thanks
Instead of using res.sendfile 'xml/foo.xml', you'll have to use a template file and pass your variables into a library that will parse the template and give you the XML for each request. While there are many templating engines for Node.js, the two that Express supports by default are EJS and Jade. Jade is Haml-like, which is cool, but if you're working with existing XML, then you should probably stick to EJS. EJS lets you just take ordinary HTML or XML and embed JavaScript in it.
So, you'd rename xml/foo.xml to views/foo.ejs and, instead of res.sendfile, you'd write something like
res.contentType 'text/xml'
res.render 'foo.ejs', obj
where obj contains all of the variables that you want to make available to the template.
Check the Express guide on "View Rendering" for more information.

Categories

Resources