Including ejs partial with listner button not working; how to fix static? - html

I am trying to include a partial on the page with my backend coming later. I want to use an event listener button. It dosent work. I am using express.ejs and node.js with vanilla js.
I am using this for my vanilla js
const button = document.getElementById('button')
button.addEventListener('click',()=>{
const hi = document.createElement(`<%-require('../views/partials/hi.ejs')%>`)
document.appendChild(hi)
})
this for my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hi</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<button id="button">Im a button</button>
<script src="main.js" type="module"></script>
</body>
</html>
and this for my node
const express = require('express')
const app = express()
app.set('view engine','ejs')
app.use(express.static('public'))
app.get('/',(req,res)=>{
res.render('layout')
})
app.listen(5000,()=>{
console.log('server listening')
})
I get this error when i try to use the partial with the button
main.js:4 Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('<%-require('../views/partials/hi.ejs')%>') is not a valid name.
at HTMLButtonElement.<anonymous> (http://localhost:5000/main.js:4:25)
this comes from client side....why and how to fix?

Related

Ajax on nginx causes 404 not found

I'm using ajax to update a value without refreshing the page.
When I use this html code the website gives an 404 not found error. But when I leave the script tag out of the html, the site works fine and show the p tag. What am i doing wrong in the script tag?
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smart_home</title>
</head>
<body>
<div id="verbruik">
<p></p>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
document.getElementById("verbruik").innerHTML =
this.responseText;
}
xhttp.open("GET", "/home/pi/smart_home/ajax_info.txt", true);
xhttp.send();
setTimeout(loadDoc, 2000);
}
loadDoc();
</script>
</body>
</html>

Flutter Web: SPA: using URL parameters in meta data tags

I would like to get the parameters in a URL and use them to generate an og:image meta tag in my SPA. The specific purpose is to have a dynamic thumbnail for a given url. The idea is for crawlers to be able to find the appropriate thumbnail.
example URL:
https://my.app/#/post?uid=abc&pid=123
These two parameters will not necessarily always be included. I hope it won't cause an issue.
My understanding is that crawlers generally only check the html for metadata. How could I include a bit of code in my html before the metadata? (I am relatively new to HTML)
Would I be able to put a script in the head tag? Are variable in the script available outside of the script? Can I use variable in the URL address of my og:image tag?
<!DOCTYPE html>
<html>
<head>
<meta property="og:image" content="https://my.app/{uid}/{pid}/thumb.png" />
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Get Dressed. Better than you ever had">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="vestiqweb">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="shortcut icon" type="image/png" href="favicon.png"/>
<title>VESTIQ</title>
<link rel="manifest" href="manifest.json">
</head>
<body id="app-container">
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script>
var firebaseConfig = {
//config info
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="main.dart.js?version=14" type="application/javascript"></script>
</body>
</html>
I was able to put a script before the meta tags and used window.location.href to get the URL. I used URLSearchParams to extract the parameters. However, I can only get the second parameter and not the first. If I add an '&' before the uid it works, but makes the url look weird... "?&uid"
<script>
const queryString = window.location.href;
const urlParams = new URLSearchParams(queryString);
const uid = urlParams.get('uid')
const pid = urlParams.get('pid')
if (uid != null && pid != null)
document.getElementById('urlThumb').content = `https://my.app/posts%2F${uid}%2F${pid}%2Furl_thumb.jpg?alt=media`;
</script>

res.sendFile not rendering html

I am trying to render HTML with res.sendFile using absolute path but it is sending encoded HTML in a pre tag so the response shows HTML unrendered in a pre tag.
Here is my express code
app.get('/', (req,res) =>{
res.sendFile(__dirname+'/a.html');
});
and here is my html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>I am Html</h1>
</body>
</html>
and here is the result when I navigate to localhost:8800/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>I am Html</h1>
</body>
</html>
It prints the html as it is without rendering it.
You need to use res.render() to actually render the html.
I can't post a comment because I don't have enough reputation, but what I was going to say is that I ran your code on my system (OSX Mojave 10.14.6, Node v12.13.0, latest versions of Firefox and Chrome) with some additions to make it work (posted below), and didn't run into your problem. Perhaps you have some other code or middleware that you haven't posted. Also, you are correct that res.render is for templates.
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/a.html');
// better to use the path API, but both work
// res.sendFile(path.join(__dirname, 'a.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
The HTML is the same. Folder structure is:
.
├── app.js
├── a.html
Could you post more details?

Putting the values of nodejs var in html

I'm trying to use nodejs to read the IP address and display on a html page, here is what I've done so far:
app.js
const express =require('express')
const app = express();
var os = require( 'os' );
var path = require('path')
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'))
})
var networkInterfaces = Object.values(os.networkInterfaces())
.reduce((r,a)=>{
r = r.concat(a)
return r;
}, [])
.filter(({family, address}) => {
return family.toLowerCase().indexOf('v4') >= 0 &&
address !== '127.0.0.1'
})
.map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);
app.get('/DHCP',(req,res)=>{
return networkInterfaces[1];
});
app.listen(1000)
and the index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
<script src='main.js'></script>
</head>
<body>
<p id="DHCP" align="middle"> DHCP:</p>
</body>
</html>
I'm new to web dev world so I just don't get how can I do it !
thanks in advance !
You need to pick a template engine (e.g. pug), then call res.render() with an html template modified according your template engine's syntax.
use something like this:
<p id="DHCP" align="middle">{{DHCP:}}</p>
This works if you previously set your application to use HTML instead of any View Engine.

Display Heading and Description of a HTML template reading from JSON

I am working on a simple webpage. I have a following sample json file and an HTML template
data.json
{
"NAME":"SAMPLE_NAME",
"ADDRESS":"New Brunswick Avenue"
}
index.html
<div class="name"></div>
<div class="address"></div>
So i have to display the name and address on the template reading from the json file. Is there any library that i can user for this or any other way to accomplish this?
I think you are looking for a compile-time templating or pre-compiled templating engine sort of thing.
You can build one your own with html, css and using javascript or jquery to change the text of certain elements, but this is going to take a long time if you have big pages.
However there is a library out there that does something like this and its called Handlebars.
Heres a link: http://berzniz.com/post/24743062344/handling-handlebarsjs-like-a-pro
This might give you an idea of what it does: What is the difference between handlebar.js and handlebar.runtime.js?
Here is an example using your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// Load your html / template into this variable
var template = '<div class="name">{{name}}</div><div class="address">{{address}}</div>';
var jsonData = {
"name":"John",
"address": "City Street"
}
var compiledTemplate = Handlebars.compile(template);
// The output html is generated using
var html = compiledTemplate(jsonData);
document.getElementsByTagName('body')[0].innerHTML = html;
</script>
</body>
</html>
If you would rather write html outside of the javascript variables you could also do it like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="template">
<div class="name">{{name}}</div>
<div class="address">{{address}}</div>
</div>
<script>
// Load your html / template into this variable
var template = document.getElementById('template').innerHTML;
var jsonData = {
"name":"John",
"address": "City Street"
}
var compiledTemplate = Handlebars.compile(template);
// The output html is generated using
var html = compiledTemplate(jsonData);
document.getElementById('template').innerHTML = html;
</script>
</body>
</html>