bootstrappedUser - Jade or EJS to HTML - javascript

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;
});

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 )

How can I make a POST request to a php file within the same angular application?

I have a strange situation where I need to send some image data to a php file from within the angular application itself... yes, the php file resides in the angular docroot.
Every time I try to upload image data (from the browser) to this file, the application doesn't seem to go through to it. Instead, I get back a response that is the entire index.html code. I understand that this is probably because I am using ui.router to handle my routing, and have it defaulting to index.html. However, I have tried to add app.use("/upload.php", express.static(path.join(__dirname, '/upload.php'))); to my node server script... in hope that the /upload.php url would be succesfully routed... however, I still only get back index.html code and it seems that the upload.php file is never reached.
Can anybody provide any hinters? Much appreciated.

Using external js libraries in sapui5

So I'm trying to inlcude an external .js file in my SAPUI5 Controller.
jQuery.sap.includeScript("externalLibrary.min.js",
function() {
//initalizing objects from library
});
However, the callback which should be called once the script is loaded, never gets called. The error message it gives me is:
"externalLibrary.min.js:16 Uncaught TypeError: Cannot read property
'Constructor' of undefined"
Whats another way I could do this? I was looking into jQuery.sap.registerModulePath() and jQuery.sap.registerResourcePath() but couldn't find a good example of the use of these nor an explaination of the difference between the two online.
Thanks a lot!
You can try jQuery.sap.includeScript(vUrl, sId?, fnLoadCallback?, fnErrorCallback?)
https://sapui5.hana.ondemand.com/docs/api/symbols/jQuery.sap.html#.includeScript
in fiori launchpad based app , we use component.js as root , so we don't have index.html to include scripts (if you use XML view instand of HTML view).
try
jQuery.sap.includeScript({
url: "https://maps.googleapis.com...",
id: "IncludeGoogleMapsScript"
}).then(function() { ... })
Not working in portal service , fallback is provided :
UsingjQuery.sap.includeScript().then() in HCP Firori Launchpad
You can use jQuery.sap.registerResourcePath('lib', URL) and then jquery.SAP.require('lib.file'). You can do both one after another or register in the init and later require. Does not matter. I don't have an example at hand as I am on a phone but it works. What you need to keep in mind is that this example would load something like URL/file.js so you need to adjust accordingly. The name you give to the lib does not matter.
You can also inject a script tag into the current page ,however, the require will load the external lib synchronously while if you inject a script tag you need to wait until it is loaded with a callback.
PS: the capitalization on those methods is not right
Got it! For future reference, it works to load the files from the index html like so:
<script src="library.js"></script>
The main problem was that I was trying to include external dependencies which also contained jQuery. So, I had to remove that from the file and now it's working.

Jade: load external javascript and call function

I was learning Express/Node/Jade and now in the Jade file I want to include a javascript file from the public folder just for the page.
For example, in jade file I type this:
script(src='/javascripts/test.js')
and inside test.js I have a function
function check_test(){
return "It's working!"
}
then I try to call the function in Jade by
- var test_response = check_test()
than I got the error saying that "undefined is not a function" and test.js isn't load at all.
Apparently Jade doesn't load the file, they only transform into HTML code.
I look someone else's question and this is the closest one I can found but it doesn't provide a clear answer of what to do.
In Jade, how can you call a function in an external Javascript
So my question is: In this case what should I do to make it work?
I don't want to load the file in layout.js since I only want test.js only be use by this page.
Well... In the first instance, it is different what happens in the browser of what happens on the server. So Jade is a rendering of HTML, therefore if you are in the browser. It's what ExpressJS shipping, ie rendering Jade. If you want to call, your HTML Javascript (Rendering of Jade), should show you where the Javascript. For exmaple
in Server.js
// Get the Javascript in the browser
app.use("/javascripts", express.static("./outJavascripts"));
// Get the URL
app.all("/", function(req, res){
// Render the Jade and Send for the client (Browser)
req.render("myTemplate.jade");
});
In myTemplate.jade
script(src='/javascripts/test.js')
In "./outJavascripts/test.js"
function check_test(){
console.log("It's working! :D");
return "It's working!";
}
If you do this, you will realize that it is run, the file "./outJavascripts/test.js" in the browser. And the function "check_test" never run in the server.
Or put all folders in a common folder, for example public
public
-javascripts
-stylesheets
-images
and then expose that public folder
app.use(express.static(path.join(__dirname, 'public')));
which means you can
script(src='/javascripts/script.js')
link(rel='stylesheet', href='/stylesheets/style.css')
Save your JS file and link it in your Jade file as:
script(src="filepath/yourJSfile.js")
Then call the function, I'm using a button here for example:
button(class="btn", onclick='functionName()')

Need to understand how tracking codes may be working in web content

I was recently approached by a web partner and they asked me to add their 'tracking code' to my site as shown below. The data and address would be different, but the structure is the same as below. Currently they load our site in an IFrame and what I can't understand is...
How could the script portion provide any value to them? Can a parent page read JavaScript state of something in a hosted IFrame? Google uses a similar pattern but they set the src which has Script that is executed when the page loads and could read the state.
Can anyone explain how this might be working or is this just useless page spam?
<img src="https://www.APartnerCompany.foo/thing.img?arg=value" />
<script type="text/javascript">
//<![CDATA[
var Foo = {};
Foo.Tracking = {};
Foo.Tracking.Sale = {};
Foo.Tracking.Sale.amount = '100.00';
//]]>
</script>
An inline script can also read values from the page it is contained in. To post them back to their own server, they seem to use the src attribute of that affiliate image. However, the pieces you provided are harmless (the code does nothing than constructing an object) and requests only a non-executable from https://www.APartnerCompany.foo/thing.img?arg=value (beeing logged at theirs).
When the request for that src is being sent the server is just logging the variables that are accompanied with it, the JS code is just updating the arguments with relevant data.
All it does is send information to a server through a GET request which it is logged. It can be as simple as reading the Apache logs for hits or it can be a cgi that processes the data. That is basically how all those ad/logging services work.

Categories

Resources