Rendering HTML + CSS with Node Express - html

I am using res.sendFile() to render my HTML page but the css styles are not being rendered as well.
I trie looking online for help and saw some people suggesting the use of express.static() to turn the files folder into a static one and that would make the css render, but honestly I didn't fully understand. I don't know if the css and html need to be on the same folder or not, or even how to structure the code after using static(). Can someone help me out?
Here's a snippet of the code
const express = require('express');
const userControl = require('./controller/userControl');
const routes = express();
routes.get('/login', (req, res)=>{
res.sendFile('login.html', {root: '../pages'});
});
Here's my file structure
(https://i.stack.imgur.com/R4mLY.png)

Related

Add an html file to the build version of react

I have a landing file which is in pure HTML. (landing.html)
I want the main URL of the website to be this file and the rest of the URLs to go in the React app.
For example:
example.com -> landing.html
example.com/app -> react app
example.com/login -> react app
As I said, I want the main URL to read the landing.html.
But the rest of the app should read the build version of React.
If it's possible i want it to be a part of the React app and not adding it directly in build folder. After running build it should be automaticly in build folder so basicly kinda implicitly to be a part of react app.
One more thing I dont want to convert it to jsx. 😁
How can I implement this ?
For the landing page use
var __html = require('./template.html');
var __html = require('./template.html');
var template = { __html: __html };
React.module.exports = React.createClass({
render: function() {
return(
<div dangerouslySetInnerHTML={template} />
);
}
});```
on / route and other react components use on app and login route
I researched a bit and found two solution for it.
First : Using multipage app feature in Vite.
Second: confining nginx on server for this feature. (I didn't do the configuration someone else did, but it worked)

How to convert HTML to image in Node.js

I need to convert an HTML template into an image, on a Node server.
The server will receive the HTML as a string. I tried PhantomJS (using a library called Webshot), but it doesn't work well with flex box and modern CSS. I tried to use Chrome headless-browser but it doesn't seem to have an API for parsing html, only URL.
What is the currently best way to convert a piece of HTML into image?
Is there a way to use headless Chrome in a template mode instead of URL mode? I mean, instead of doing something like
chrome.goTo('http://test.com')
I need something like:
chrome.evaluate('<div>hello world</div>');
Another option, suggested here in the comments to this post, is to
save the template in a file on the server and then serve it locally and do something like:
chrome.goTo('http://localhost/saved_template');
But this option sounds a bit awkward. Is there any other, more straightforward solution?
You can use a library called Puppeteer.
Sample code snippet :
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({
width: 960,
height: 760,
deviceScaleFactor: 1,
});
await page.setContent(imgHTML);
await page.screenshot({path: example.png});
await browser.close();
This will save a screenshot of the HTML in the root directory.
You can easily do it on frontend using html2canvas. On backend you can write the html on a file and access using a file URI (i.e: file:///home/user/path/to/your/file.html), it should work fine with chrome headless-browser and Nightmare (screenshot feature). Another option is to setup a simple HTTP server and access the url.

Why would my page have different dimensions when run from the server?

file:///Users/dg/Google%20Drive/code/websites/Q-Po/qpo/client/index.html
I have a page. When I access it from my local file system (via file:///*), pull up my developer console in Chrome, and type window.innerWidth, the result is 1162.
When I serve the same page from a Node server in the cloud via Express.js, like this...
var express = require('express'); //Require express for middleware use
const app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http); //IO is the server
app.use(express.static(__dirname + "/../client")); //Serve static files
app.get('/', function(req, res){
res.sendFile('./index.html');
});
... and then access it my browser at [url].com, I get window.innerWidth = 1278.
This apparently causes the served version of the page to scale down svg elements slightly (shown below.)
What gives?
local page (clipped horizontally -- focus on difference in scaling of elements in center between this and the below image:)
served page (also clipped horizontally)
The svg containers in the middle of the page are both 600x600, according to the element inspector, but they render at different actual sizes on my screen. How can this be?

Using Onsen, how to write server side code in NodeJs that will render Jade files as HTML in a splitter

In my Onsen app I have the following splitter. I am using Jade, and rendering all the other pages from the list items in html (despite the fact that they are in separate jade files) by including the files at the bottom of the page, as shown below:
body(ng-controller='...')
ons-splitter(var='mySplitter')
ons-splitter-side(var='menu' side='left' width='220px' collapse swipeable)
ons-page
ons-list
ons-list-item(ng-click="root.load('home.jade')", tappable='')
| Home
ons-list-item(ng-click="root.load('search.jade')", tappable='')
| Search
... more list items
ons-template(id='home.jade')
ons-page(ng-controller='...')
ons-toolbar
.left
ons-toolbar-button(ng-click='mySplitter.left.open()')
ons-icon(icon='md-menu')
.center
| My App
//- google maps stuff
ons-input#pac-input.controls(type='text', placeholder='Search Box')
div#map.col-md-12
ons-bottom-toolbar
.center
| MyApp
include search.jade
I believe this is a dirty shortcut, and will load the contents of search.jade (as well as every other file I include) before the user even clicks the item in the splitter.
I do not want this functionality. I would like to instead have server code in NodeJs that renders the jade files in html when they are ready to be displayed to the user. Something like this:
jade.renderFile('search.jade')
This angular code is currently how I am loading the page from the item in the splitter:
mySplitter.content.load(page)
.then(function() {
$scope.pop = page;
mySplitter.left.close();
});
However I am very confused about how to write this in a node route. Do I just abandon the splitter function in angular?
Can anyone help clarify this for me and show me a clear example of how to write the node route to render the jade files as html each time they are loaded?
Please see solution 1 of the selected answer from this stack overflow post for a reference of what exactly I am trying to do: stack overflow post
I am currently using solution 2 from that post.
I believe this is the relevant code in server.js:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
However when I change jade to html, I receive the error:
Error: Cannot find module 'html'
All my front-end files in the views folder have .jade extensions and are written in jade.
Update
Here is how I am serving index.jade (which is in the views folder) in a file called index.js:
module.exports = function(app){
/* Get home page. */
app.get('/', function(req, res, next) {
res.render('index', { title: 'My App' });
});
}
This was my old route NodeJS route which is no longer being used because of the splitter:
// get user search page
app.get('/user/search', function(req, res, next) {
return res.render('searchForTrainer');
});
Hmm. Since your code seems relatively small I would guess that what it does may be just serving all your files from views and actually "rendering" them. So probably you are just failing to access them properly later on. Maybe you have a url like /search.html or /search (instead of /search.jade). Could you try to confirm whether you can access such a url?
Also is your index.jade file served in some other way like startingPoint: 'index.jade' or something similar or is it also located in the views folder?
Basically as long as your index file has the same treatment as your other views then everything should be fine.
Update:
With what you just provided we can see the way in which you are serving your index.
app.get('/', function(req, res, next) {
res.render('index', { title: 'Fitness App' });
});
The equivalent of that is exactly the same as what you said you had before:
app.get('/user/search', function(req, res, next) {
return res.render('searchForTrainer');
});
Here res.render is what converts your jade into html and then returns it to the client. Since the splitter is expecting html that means you shouldn't have made changes to the server when you started using it.
Here is how the process looks like:
Client | HTTP | Server
| |
content.load('page') → GET /page ↘
| | res.render('page') // convert jade to html
html is loaded ← 200 OK html content ↙
in splitter.content | |
TL;DR - if you use your old route everything should be fine. Just remember to change the page url in the splitter from search.jade to /user/search (or whatever the url for will be).

Node js hbs module and engine

I'm new to node js and came across this hbs module and saw it in this part code for example :
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
can anyone please explain what is hbs (handlebars - but what does it do)?
and why the second line is needed if the first already says that the files will be opened as html
Thank you!
hbs is a express.js wrapper for the handlebars.js javascript template engine. Handlebars.js is a template engine to make writing html code easier, if intrested you can look here. But handlebars.js is meant for client-side copilation(the browser compiles the templates) so you need a wrapper like hbs.
A wrapper makes it possible to use for example a client-side library in express.js and that is what hbs does. This was a little simplify, but it explains the principle.
Over to your second question, why the second line is needed. and that is because if you use the standard line:
app.set('view engine', 'hbs');
express.js looks for the view engine named hbs, but in your example:
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
express.js dosent know what to look for in case of the view engine defined as html and you have to define this view engine in the second line, so express.js knows what to look for. If you look here, you can see that it says, Express loads it internally.