ExpressJS: call a variable from .js file to index.html - javascript

I am using express#4.16.2
I want to call a variable from main.js to index.html
main.js:
const express = require('express')
const app = express()
var router = express.Router()
app.use('/',express.static('public'));
app.get('/main', function(req, res) {
res.send("index", {name:'hello'});
});
app.listen(3000, () => console.log('listening on 3000'));
index.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">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>
<body>
<<h1>{{ name }}</h1>
</body>
</html>
This is giving the following result on the webpage:
{{ name }}
Is there an http get method call that I need to make? What am I missing in between? Any help/hint/guidance would be highly appreciated!
Thanks

You have to use a template engine that let you replace variables in the view file with actual values, and transform the template into an HTML file sent to the client.
There are many view engines work in combination with express, you could choose one of them here: https://expressjs.com/en/guide/using-template-engines.html
I suggest you to use ejs since it's very easy to understand, Here is an example using it:
main.js
const express = require('express')
const app = express()
var router = express.Router()
app.use('/',express.static('public'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/main', function(req, res) {
res.send("index", {name:'hello'});
});
app.listen(3000, () => console.log('listening on 3000'));
index.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">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>
<body>
<!-- show name -->
<<h1><%= name %></h1>
</body>
</html>

You are using hbs syntax:
<<h1>{{ name }}</h1>
without ever loading the hbs view engine to render it.
example for hbs:
const express = require('express');
const hbs = require('hbs');
const app = express();
app.set('view engine', 'hbs');
app.get("/main", (req, res) => {
res.render("index.hbs", {
name: "hello"
});
});
app.listen(<port>);

Related

applying styling for markdown in express/nodejs

I'm trying to load a markdown file as a static file which should afterwards be rendered via a html file. My question now is how I am to apply CSS Styling. Here is my code for the index.js:
const express = require('express');
const bodyparser = require('body-parser');
const showdown = require('showdown');
const marked = require('marked');
const app = express()
app.use(express.static(__dirname + '/'));
app.use(bodyparser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.use(express.static('public'));
app.get('/article', (req,res)=> {
var markdown = require("markdown-js");
var fs = require("fs");
var path = __dirname+'articles/article.md'
app.use(express.static("public"));
fs.readFile(path, 'utf8', function(err, data) {
if(err) {
console.log(err);
}
//res.send(marked("" + data));
//console.log(result);
res.render('index.html');
});
});
// listen to port
const PORT= 3000;
app.listen(process.env.PORT || 3000, function(){
console.log('server is running on port 3000');
})
The code for my current html file looks the following such that index.html:
<!DOCTYPE html>
<html lang="en">
<script src="style.css"></script>
<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>
<% result %>
</body>
</html>
In order to use variables you have to use ejs you can read about it here https://ejs.co/
then you can do something like this:
First change the name to index.ejs
Then you have to pass the data
res.render("index", { result: data })

Svelte don't load components with node.js

I want to build an application with Node.js and Svelte, but when I try to import a component it wasn't load.
Server side code:
const app = require("express")();
const http = require("http").Server(app);
const port = process.env.PORT || 8080;
const io = require("socket.io")(http);
const fs = require('fs')
const express = require('express')
app.get('/', (req, res) => {
res.write(fs.readFileSync('./pages/homepage.svelte', 'utf-8'));
res.end();
});
io.sockets.on('connection', function (socket) {
console.log('Utente connesso!')
});
http.listen(port, function() {
console.log("Listening on *:" + port);
});
Homepage.svelte:
<script>
import Component from './components/Component.svelte'
</script>
<!DOCTYPE html>
<html lang="it">
<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>SocialTree</title>
</head>
<body>
<Component />
</body>
</html>
Component.svelte code:
<div>
<h1>Test</h1>
</div>
Thanks in advice and sorry for bad english!

Socket.io Connection Event Not Triggering

I am new to using socket.io and I have tried to set up a basic functionality according to the docs and youtube tutorials. My program is supposed to console log "New socket connection" when I navigate to the index page. However, the event is not triggering. Am I missing something? Thanks!
My app.js file
const express = require("express");
const socket = require("socket.io");
const http = require("http");
const moment = require("moment");
const app = express();
const server = http.createServer(app);
const io = socket(server);
app.set("view engine", "ejs");
// Set static folder
app.use("/public", express.static("public"));
app.get('/', (req, res) => {
console.log("Reached index page")
res.render("index")
});
app.get('/room', (req, res) => {
console.log("Reach room page")
res.render("room")
});
// Run when a client connects
io.on("connection", (socket) => {
console.log("New socket connection")
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running. Navigate to localhost:${PORT}`));
My index.ejs file
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<link rel="icon" href="../public/">
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../public/index/css/index.css" />
</head>
<body>
click here
<script>
var socket = io(); // this line is supposed to be sufficient to trigger
// the socket connection
</script>
<script src="../routes/index.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
The error resulted from my naming my variable 'socket' when importing the socket.io dependency. The socket param in the line 'io.on("connection", (socket)' is supposed to reference another socket variable not the one that I created. Common practice is to name the dependency variable 'socketio' instead of 'socket'

How to impor module html router express js?

I tried importing modules but they were not found
const express = require('express');
const app = express();
const view = __dirname + '/view/';
app.get('/', function (req, res) {
res.sendFile(path.join(view + 'home.html'));
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<h1>ok</h1>
</body>
<script>
import data from 'input-plugin-date';
</script>
</html>
how do I import plugins or anything on the express router because I need them

"Error: No default engine was specified and no extension was provided" When trying to do Server Side Rendering in React

Hi I'm trying to do server-side rendering in my react app but I get the error
Error: No default engine was specified and no extension was provided.
I've got an ejs template index.ejs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello Redux</title>
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cyborg/bootstrap.min.css" rel="stylesheet" integrity="sha384-D9XILkoivXN+bcvB2kSOowkIvIcBbNdoDQvfBNsxYAIieZbx8/SI4NeUvrRGCpDi" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app"><%- myHtml -%></div>
<script src="bundle.js"></script>
</body>
</html>
A request handler function:
'use strict'
import axios from 'axios'
function handleRender(req, res){
axios.get('http://localhost:3001/books')
.then(function(response){
var myHtml = JSON.stringify(response.data);
res.render('index', { myHtml })
})
.catch(function(err){
console.log('#Initial Server-side rendering error', err);
})
}
module.exports = handleRender;
And in app.js I require the request handler function and set it:
app.set('view engine', 'ejs');
app.use(requestHandler);
Can anyone help me with this issue? The link to my github repo with all the code is at https://github.com/edward-hong/book-shop
in app.js
var app = express();
app.use(logger('dev'));
var apiProxy = httpProxy.createProxyServer({
target: 'http://localhost:3001'
});
app.use('/api', function(req, res){
apiProxy.web(req,res)
})
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
just move app.set('view engine', 'ejs') and put it right after var app = express()
apiServer.js is your entry, so you need to explicitly app.set('view engine', 'ejs') there

Categories