applying styling for markdown in express/nodejs - javascript

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

Related

CSS file is not connecting in an express app

When running my app.js file
const express = require('express');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})
this is my index.html file is
<!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>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<h1> Testing CSS</h1>
</body>
</html>
then I can not observe the changes of CSS file on the page. But when I open the HTML file with live serever I can see the CSS changes why is this happening.
When I am running my app.js file css is not connecting. But when I open the HTML file with live server CSS file is connecting. What is the reason behind this ??
app.use(express.static(path.join(__dirname, 'public')));
include this in your app.js create a folder called public and put the style.css in your public directory.
your code would be
const express = require('express');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public'))); //<-here
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})

I have an css 404 error with my website but the css exsits

I have question with express
server.js
const express = require('express')
const app = express()
const port = 8080
app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use('/img', express.static(__dirname + 'public/img'))
app.set('views', './views')
app.set('view engine', 'ejs')
app.get('/signin', (req, res) => {
res.render('signin')
})
app.listen(port, () => {
console.log('server is listening to port: 8080')
})
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.end('404 - Not Found');
return;
}
// respond with json
if (req.accepts('json')) {
res.json({ error: 'Not found' });
return;
}
});
File structure
public
css
signin.css
img
js
views
signin.ejs
server.js
signin.ejs
<!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>
<link rel="stylesheet" href="../public/css/signin.css">
</head>
<body>
<h1>works</h1>
</body>
</html>
signin.css
body{
color: yellow;
}
and the error is
http://localhost:8080/public/css/signin.css [HTTP/1.1 404 Not Found 4ms]
Can someone help me?
What is the error
I can identify two issues.
First is that the code just concatenates __dirname + 'public/css'. The __dirname does not include a trailing slash, so if your path is /home/foo, you'll get a path like /home/foopublic/css. Use path.join() instead.
Second, the HTML appears to refer to the CSS file relative to the location of the HTML on your disk. As there is already a handler for the path /css set which serves files from the css directory on your disk, the correct path would be /css/signin.css instead of ../public/css/signin.css.
So, on the node.js side:
const path = require('path')
app.use('/css', express.static(path.join(__dirname, 'public/css')))
app.use('/js', express.static(path.join(__dirname, 'public/js')))
app.use('/img', express.static(path.join(__dirname, 'public/img')))
Although you don't really even need these, as there app.use(express.static('public')) middleware already serves the files and directories from the public directory.
And the HTML:
<link rel="stylesheet" href="/css/signin.css">

Sending data object to another page using nodeJS and EJS

SI have an express server running. In the app.post ('/ login'), I have a data object that has a name and a password which i obtained from a form. I would like to forward this data to another EJS page.
app.js --> server
const express = require('express');
const app = express();
const port = 3000 || process.env.PORT;
app.use(express.json());
//Set the views + engine
app.set('views', './views');
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index');
});
app.get('/about', (req, res) => {
res.render('about');
});
app.post('/login', (req, res) => {
const data = req.body;
res.render('about', {data: data}); //i want to send this data to the about page and priew it on the screen
});
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
})
about.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Data</h1>
<p><%= data %></p> <!--Preview to entred data from the user here-->
</body>
</html>

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

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

How to get into html source code by rest request

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

Categories