how to pass variable from nodejs to html directly without using pug? - javascript

I need to pass a variable from a NodeJS file to a rendered html file. How to do that?
Here below what I had tried
Nodejs code
const loginRouter= express.Router();
const config= require('../config/config.json');
loginRouter.get('/', (req,res)=>{
res.render(path.dirname(__dirname)+'/views/login.html',{version:config.version});
//res.json('done')
});
HTML Code
<label style="font-size:10px;float: right;"><%= version %></label>
Current Result:-
Nothing is coming
Expected Result:-
<label style="font-size:10px;float: right;">3.9</label>
I have set this version number in my config which I have imported in my login.js, but still, I am not getting the output. Does anyone have any idea about it?

If you don't want to use a templating engine like ejs or pug then you can just send a get request with axios or fetch to your node server and send a response.
Here's a sample on how you can do it. Change it according to your needs.
index.html
<!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 id="title">My page</h1>
<script>
fetch('http://localhost:5000/version').then(function(response) {
return response.json();
}).then(function(myJson) {
document.getElementById('title').innerHTML = myJson;
});
</script>
</body>
</html>
server.js
const express = require('express');
const app = express();
const PORT = 5000;
app.get('/', (req, res) => {
res.sendFile('index.html', {root: __dirname });
});
app.get('/version', (req, res) => {
const myVersion = 'My version is 0.5';
res.json(myVersion);
});
app.listen(PORT, () => {
console.log(`Server running on PORT ${PORT}`);
});

Related

Handlebars handler for dropdown onchange event not working

I'm using Express with Handlebars for front-end. When the selected option in the dropdown in home.handlebars changes, I want to trigger an event and read the value of the selected option in index.js. As I understand, I should use a Handlebars helper for this. I created a helper server.js (the Node.js backend) and added it to the onchange event for the dropdown. However, the handler does not seem to work. Here is my code:
server.js:
const express = require('express');
const app = express();
const handlebars = require('express-handlebars');
const port = 3000;
app.use(express.static('public'));
var handlebarsHelpers = handlebars.create({
helpers: {
dropdownChange: function (value) {
console.log("helper running.");
console.log("value is " + value);
return value;
}
}
});
app.engine('handlebars', handlebarsHelpers.engine);
app.set('view engine', 'handlebars');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('home', {layout: false});
});
<...>
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
});
index.js:
import * as d3 from "https://cdn.skypack.dev/d3#7";
import axios from 'https://cdn.skypack.dev/axios';
const dataSet = async function getData() {
return await axios.get('/data');
}
var courseData = [];
function getNodes() {
//************************getNodes is the function that should eventually read the dropdown value************************
}
async function drawGraph() {
const data = await dataSet();
console.log(data);
courseData = data.data;
console.log(courseData);
}
drawGraph();
home.handlebars:
<!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>Graph Chart</title>
</head>
<body>
<h2 align="center">Graph Chart</h2>
<div>
<select name="select" id="select" onchange={{dropdownChange value}}>
<option value="">Select a course...</option>
<option value="course1">course1</option>
<option value="course2">course2</option>
</select>
</div>
<svg class="prereq-graph"></svg>
</body>
</html>
<script type="module" src="./static/js/index.js"></script>
How do I fix the issue of the Handlebars helper not working? Alternatively, are there other ways to pass the dropdown selected value from Handlebars to Express when the onchange event is triggered?
Thank you.
Nevermind, I remembered that Javascript's addListener is a thing and solved my issue 🙃

Node js SSR not rendering

I have a bit of code that should load a page and show an image(from server storage), that sometimes changes(is replaced by another image with the same name).
main.js:
const app = express();
const ejs = require('ejs');
var fs = require('fs');
const port = 8000;
// Render index.ejs file
app.get('/', function (req, res) {
// Render page using renderFile method
ejs.renderFile('index.ejs', {},
{}, function (err, template) {
if (err) {
throw err;
} else {
res.end(template);
}
});
});
// Server setup
app.listen(port, function (error) {
if (error)
throw error;
else
console.log("Server is running");
});
index.ejs:
<html lang="en">
<head>
<title>Fasole LIVE</title>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<img src="live.png" class="live" id="live">
<script>
while(true)
{document.getElementById("live").src("live.png")}
</script>
</body>
</html>
What am I doing wrong?

simple node client server communication not working using express and socket.io

I'm trying to write a simple client server application.
That's the 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>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
server.js file:
const express = require('express');
const app = express();
const port = 3000;
const server = app.listen(port);
const io = require('socket.io')(server);
app.get('/', (req, res) => {
res.send('Hello World!');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
client.js file:
const socket = io('https://localhost:3000/');
At this moment if I start the server by typing node server on the terminal and I open the HTML file using the LiveServer vs extension, the console doesn't show the text a user connected, it also returns an error which is:
GET
https://localhost:3000/socket.io/?EIO=4&transport=polling&t=NdZ4wOd
net::ERR_SSL_PROTOCOL_ERROR
I don't know what I'm doing wrong.
In the client.js file you could try const socket = io.connect(); and I'm not sure but i think <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script> Should be in the header but i could be wrong about that.
**Make Changes In Your Server File **
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
const server = app.listen(port);
const io = require('socket.io')(server);
app.get('/', (req, res) => {
res.send('Hello World!');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
Install cors npm package before starting your server using npm i cors

why the REST API as a body gets undefined?

I writirng server in Express to posibility GET and POST. In Insomnia I get and post valid data.
This is code my REST.
const express = require('express');
const app = express();
const port = 3000;
var cors = require('cors');
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended: true}));
let myValue = 1;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
//GET
app.get('/get', (req, res) => {
return res.json({"wartosc": myValue})
});
//POST
app.post('/post', function (req, res) {
myValue = req.body.value;
console.log(req.body)
return res.json({"wartosc": myValue});
});
Then I creaeted page with two input will be used to call the GET and POST methods of our REST server.
async function getMethod() {
let inputValue = document.getElementById("inputValue").value;
const responseGet = await fetch('http://localhost:3000/get');
const myJsonGet = await responseGet.json();
//console.log(JSON.stringify(myJsonGet));
document.getElementById("inputValue").value = myJsonGet.wartosc;
}
async function postMethod(){
let inputValue = document.getElementById("inputValue").value;
let responsePost = await fetch('http://localhost:3000/post', {
method: 'POST',
body: {'value' : JSON.stringify(inputValue)}
});
}
<!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>
<input type="text" id="inputValue">
<button onclick="getMethod()"> GET</button>
<button onclick="postMethod()">POST</button>
<script src="script.js"></script>
</body>
</html>
When I do get , I get the correct value, but when I change the value and send a post, the server prints undefined.
I don't know why, will you try to help me?
In your script.js postMethod() you should stringify the entire body:
body: JSON.stringify({'value' : inputValue})
Ideally you use querystring.stringify instead but this should also work fine.
Alternatively, you can just leave out the entire script.js with the async stuff.
Instead try with using a form and name="value". You can change the form action and method per button.
<!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>
<form method="GET" action="http://localhost:3000/get">
<input type="text" id="value" name="value">
<button type="submit">GET</button>
<button type="submit" formmethod="post" formaction="http://localhost:3000/post">POST</button>
</form>
</body>
</html>
I did some changes to make it work on CodeSandbox (example). Everything works.
const express = require("express");
const app = express();
const port = 3000;
var cors = require("cors");
const rand = () =>
Math.random()
.toString(36)
.substr(2);
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
//GET
app.get("/get", (req, res) => {
return res.json({ getval: rand() });
});
//POST
app.post("/post", function(req, res) {
return res.json({ postval: `${rand()}:${req.body.value}` });
});
I put HTML and JavaScript files in the public directory.
async function getMethod() {
const responseGet = await fetch("/get");
const myJsonGet = await responseGet.json();
document.getElementById("inputValue").value = myJsonGet.getval;
}
async function postMethod() {
let inputValue = document.getElementById("inputValue").value;
let options = {
method: "POST",
body: JSON.stringify({ value: inputValue }),
headers: {
"Content-Type": "application/json"
}
};
let responsePost = await fetch("/post", options);
let myJsonPost = await responsePost.json();
document.getElementById("inputValue").value = myJsonPost.postval;
}
Both when you send JSON data via GET and POST, you must extract it with response.json(). In addition, when submitting POST data, you must set a header that is JSON. Without it, the server will not recognize that the transmitted data is in this format.

Why GET response return 404 error with node server js?

I created a server.js with node js . Using Index.html i am linking css , js scripts . But after executing HTML file , I am getting 404 errors with respect to that files . But these script files is already present there in that path . I think my server code may be the problem .
This is that Directory structure :
ui ( folder ) - inside that - bootstrap , files ( folder )
server.js
ui --- bootstrap/css/bootstrap.min.css
--- files/css/myedited.min.css
--- files/css/skins/skin-blue.min.css
and inside index.html i am linking all css/js files .
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Start</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="/ui/bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="/ui/files/css/myedited.min.css">
<link rel="stylesheet" href="/ui/files/css/skins/skin-blue.min.css">
</head>
This is my server code :
var express = require('express');
var morgan = require('morgan');
var path = require('path');
var app = express();
app.use(morgan('combined'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'index.html'));
});
app.get('/ui/bootstrap/css/bootstrap.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui/bootstrap/css', 'bootstrap.min.css'));
});
app.get('/ui/files/css/skins/skin-blue.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui/files/css/skins', 'skin-blue.min.css'));
});
app.get('/ui/files/css/myedited.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui/files/css', 'myedited.min.css'));
});
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
console.log(`my app listening on port ${port}!`);
});
when i load my application , index.html is working fine . With the help of inspect element in browser , i can see response that
Cannot GET /ui/bootstrap/css/bootstrap.min.css
Cannot GET /ui/files/css/myedited.min.css
Cannot GET /ui/dist/files/skins/skin-blue.min.css
i also restarted server nothing is working . any idea ?
By placing a / at the start of your file paths, you are saying to look for them in the computer base dir, not the current one.
Just remove the /:
app.get('ui/bootstrap/css/bootstrap.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui/bootstrap/css', 'bootstrap.min.css'));
});
app.get('ui/files/css/skins/skin-blue.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui/files/css/skins', 'skin-blue.min.css'));
});
app.get('ui/files/css/myedited.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'ui/files/css', 'myedited.min.css'));
});

Categories

Resources