I have a node.js project where I need to pass data from js file to html file
js file code
const express = require('express');
const router = express.Router();
const path = require('path');
const db = require('Dal/ProductsDal');
const productsArray = db.showAll();
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/home.html') , {obj: productsArray })
})
module.exports = router;
html file code
<!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>Node.Js Concluding Exercise</title>
</head>
<body>
<h1>Welcome</h1>
<div>
products
</div>
</body>
</html>
How can I show the product array in html div?
You could read the html file from node with a file reader and look for the div tag and replace with the data.
example code below
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', 'utf-8', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
const products = 'some data';
const result = data.toString('utf8').replace('<div>products</div>', products);
res.write(result);
res.end();
});
}).listen(3000);
Using template engines with Express
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
https://expressjs.com/en/guide/using-template-engines.html
Related
I'm trying to include an icon as part of my website, currently my code looks like the following:
app.js
const http = require('http');
const fs = require('fs');
const express = require('express')
const path = require('path')
const hostname = '127.0.0.1';
const port = 3000;
const html_file = "./index.html";
var app = express()
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static('public'));
console.log(path.join(__dirname, 'public'));
fs.readFile(html_file, function (err, html) {
if (err) {
throw err;
}
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write(html);
res.end();
}).listen(port);
console.log(`Listening on http://${hostname}:${port}`)
});
While my html file looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<body>
<p>test text</p>
</body>
</html>
However, the icon is never loaded properly.
I can see that the request returns in the network inspection tab, and there are no errors from nodejs in the console, but no matter what it fails.
I've tried switching between adding and not including the /public/ in the link line too, as well as moving the HTML file to the public folder itself.
Any ideas?
You're starting a vanilla HTTP server that only serves your index.html file and nothing else.
I'd suggest moving index.html into the public folder and using app.listen() to start your Express app instead.
const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
app.use(express.static(path.join(__dirname, "public")));
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
I highly recommend working through the Express Getting Started guide.
You should also use an absolute path to your icon in the HTML
<link rel="icon" type="image/x-icon" href="/favicon.ico">
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 })
I have been doing some research on dynamically changing the meta tags for my react Js application. I have tried so many solutions such as Helmet but I have not succeeded.
I will be glad if someone can give me a clear algorithm on this task. I have two backends one is in Express and another one in PHP. I created the Express backend purposely for this task yet I have not succeeded in getting the meta tags change when I share my link to other platforms like Facebook.
My current implementation.
Frontend:
My Index.html inside public has
<title>$OG_TITLE</title>
<meta name="description" content="$OG_DESCRIPTION" />
<meta property="og:title" content="$OG_TITLE" />
<meta property="og:description" content="$OG_DESCRIPTION" />
<meta property="og:image" content="$OG_IMAGE" />
Express Backend
const express = require('express');
const cors = require("cors");
const path = require('path');
const fs = require('fs');
const app = express();
app.use(cors());
const port = process.env.PORT || 2800;
app.use('/api/dynamicmeta', (req, response)=>{
const filePath = path.resolve(__dirname, './build', 'index.html')
fs.readFile(filePath, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
data = data.replace(/\$OG_TITLE/g, 'Contact Page');
data = data.replace(/\$OG_DESCRIPTION/g, "Contact page description");
result = data.replace(/\$OG_IMAGE/g, 'https://i.imgur.com/V7irMl8.png');
response.send(data);
});
});
app.use(express.static(path.resolve(__dirname, './build')));
app.get('*', function(request, response) {
const filePath = path.resolve(__dirname, './build', 'index.html');
response.sendFile(filePath);
});
app.listen(port, () => console.log(`listening on port ${port}!..`));
module.exports = {
app
}
At this point, I am confused on how to continue because the title of my build doesn't change.
I'm sending the file to the backend (written in Express JS) using fetch API with FormData API. My application is working fine. But after clicking on the Send button, my page is getting refreshed, even though I have not used any HTML form element.
I deleted FormData inside of Send button event listener function callback, and page didn't refresh after that. I also deleted fetch api call but keeping the FormData, and then also page didn't refresh. But on using them together, page gets refreshed.
Front End Code:
<!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>Code Analyzer</title>
</head>
<body>
<h1>Insert the Code File here</h1>
<input type="file" name="myFile" />
<button class="btn">Send</button>
</body>
<script>
//Get the DOM elments
const btn = document.querySelector(".btn");
let input = document.querySelector('input[type="file"]');
let formData = new FormData();
btn.addEventListener("click", e => {
e.preventDefault();
formData.append("myFile", input.files[0]);
console.log(formData);
fetch("http://localhost:9000/analyze", {
method: "POST",
body: formData
})
.then(data => data.json())
.then(res => console.log(res))
.catch(err => console.log(err));
});
</script>
</html>
Back End Code:
//Importing Packages
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const multer = require("multer");
const app = express();
//Configuring Multer
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "uploads");
},
filename: function(req, file, cb) {
cb(null, file.fieldname + "-" + Date.now());
}
});
const upload = multer({ storage: storage });
//Middlewares
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//Routes
app.post("/analyze", upload.single("myFile"), (req, res) => {
console.log(req.file);
res.json({ Analyzed: "Yes" });
});
//Server Listening
app.listen(9000, () => {
console.log("Server started on 9000");
});
I had the same problem using create-react-app and I execute serve -s build after create a production repo, when I tried see the problem it's gone. I figure out that is in developer mode that it's happen.
I want to render some value of another website by fetching the HTML source data by REST request, console the value inside the span tag to my console log and render it to my HTML.
I can't managed to this by my current code, he receives the data before the DOM is ready and the specific san tag i need still not there.
My current code -
async function uiTagChecking() {
let url ='http://production.com:8000/loginPage#';
fetch(url)
.then(await sleep(6000))
.then(response => response.text())
.then(pageSource => console.log(pageSource));
}
The current source code I've fetched (this is before the DOM is ready and the needed span tag doesn't there yet)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>loading...</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="icon"
type="image/png"
href="images/favicon.png?v=9">
<!--<link href="assets/vendors/keylines/map/leaflet.css" rel="stylesheet">-->
<link href="XXXX" rel="stylesheet"></head>
<body>
<div id="app"></div>
<script src="assets/vendors/jquery.min.js"></script>
<script type="text/javascript" src="XXXX/index-c08574aac712ae81e016.js"></script></body>
</html>
The span tag i want to print and render -
<span class="version-for-qa">2.1.1</span>
But it appears only after the redirect is ended and the DOM is ready.
Technical info:
Node JS
JavaScript
HTML + CSS
My server file (express):
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var fs = require('fs');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
app.use(cors());
app.set(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});