problems with ejs includes and partials - javascript

I'm trying to make a dynamic include using ejs, but my css is working only on the main page (mainPage.ejs), but not on the login page (loginPage.ejs). My folders are organized as follows:
app.js below
require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const helmet = require('helmet');
const routes = require('./src/routes/routes');
mongoose.connect(process.env.DATABASE_KEY, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log('Connected to the database');
app.emit('ready');
})
.catch((err) => console.log(err));
//app.use(helmet());
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.set('views', './src/views');
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(routes);
app.on('ready', () => {
app.listen(3000);
})
Here is my head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
<link rel="stylesheet" href="css/style.css"/>
<title>Home</title>
</head>
<body>
loginPage.ejs
<%- include('./includes/head')%>
<div class="test">
donĀ“t work
</div>
<%- include('includes/footer')%>
As I said, css is only working on mainPage.ejs, and there the includes were imported as follows:
<%- include('./includes/head')%>
...html
<%- include('includes/footer')%>
In loginPage.ejs the css for some reason is not working even though the includes are exactly the same as the mainPage. I tried to see if the problem was in some configuration made in app.js, but I still couldn't solve it.

I had a similar problem recently. If someone is still struggling with this.
This is how I solved it:
Put views and css in one folder. In your case, you can put the src folder inside the public folder.
Then in app.js change -> app.set('views', './src/views'); -> app.set('views', './public/src/views');
Adjust your css and other paths in your app respectively.

Related

How to add static css to node js app by express.static

I have a node.js app with a static css file. When I create a middleware and call the css file, it is geeting an error as follows:
Refused to apply style from 'http://localhost:3000/files/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Here is my app.js file
var express = require ('express');
var app = express();
app.set('view engine', 'ejs');
app.use('/files', express.static('/files'));
app.get('/', function(req, res){
res.render('index');
});
app.listen(3000);
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>New page</title>
<link rel="stylesheet" type="text/css" href="files/style.css">
</head>
<body>
<p>New style</p>
</body>
</html>
When I use URL : http://localhost:3000/files/style.css
Display "Cannot GET /files/style.css" and when checking in the console's network tab, it says styles.css not found. This happens when I add static javascript files too.
I also tried this with follows
app.use('/files', express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/files'));
app.use(express.static('files'));
and none of them has worked so far.
How can I solve this?
You try to get file from files/files/files/style.css
Try code below:
NodeJs:
app.use(express.static(path.join(__dirname, 'files')));
HTML:
<link rel="stylesheet" type="text/css" href="/style.css">

Refused to apply style from 'http://localhost:3000/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type

I am just creating an example website template, and am getting this error in the Chrome console:
Refused to apply style from 'http://localhost:3000/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I am getting a 404 error when trying to load the css/style.css page, but the path seems correct. Below is some of the basic code for the site:
App:
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
var path = require('path');
app.engine('hbs', exphbs({extname:'hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, "static")));
app.get('/', function(req, res) {
res.render('resume.hbs')
})
app.listen(3000)
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<link rel="stylesheet" href="..\css\style.css" type = "text/css">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
CSS:
h1 {
color: blue
}
Below are what the folders look like, which shows the path. I cannot seem to find a way to fix this. Any ideas?
This is likely just caused by not having the expected path.
You're using this line here:
app.use(express.static(path.join(__dirname, "static")));
So in this case, you need a folder named "static" and inside that folder you can put your css and images. You would be able to link to them as follows:
<link rel="stylesheet" href="/css/style.css" type="text/css">
Reference: https://expressjs.com/en/starter/static-files.html
Since you are working with hbs, create "public" folder and keep your static folders, css,javaScript,img inside the "public" folder. then
const path = require("path");
app.use(express.static(path.join(__dirname, "public")));
Here is the magic, since you told express that use "public" as a static folder, when you link the files inside that folder, hbs will take "public" folder as the "root" folder.
So lets say you have main.css in folder "style" inside the folder ""public", "public/style/main.css" directory, when you link main.css:
<link rel="stylesheet" href="style/main.css" type="text/css" />
Also, this is the complete setup for hbs in express:
app.set("view engine", "hbs");
app.engine(
"hbs",
expressHbs({
defaultLayout: "layout",
extname: ".hbs",
layoutsDir: __dirname + "/views/layouts",
partialsDir: __dirname + "/views/partials"
})
);
Place all your css inside a folder - call it static or public.
So your css is located at public/css/style.css.
In your app.js, you would reference static files by:
app.use(express.static(path.join(__dirname, "public")));
The path of the public folder should be relative to the app.js file.
just make a folder called static. and put your css folder and image folder in static folder.
Don't forget to first make css folder to keep all css files and image folder for all images.
your code:
app.use(express.static(path.join(__dirname, "static")));
in this code you are saying express to look at static folder and because you don't have static folder you are getting error and your css and image are not applying on your website.
Sol:
First create a folder static and transfer css folder to static folder.
2.In html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<link rel="stylesheet" href="css\style.css" type = "text/css">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
Js file
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
var path = require('path');
app.engine('hbs', exphbs({extname:'hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static("static"));
app.get('/', function(req, res) {
res.render('resume.hbs')
})
app.listen(3000)
I tried to change the different slashes as well, but that does not entirely solve the problem. Propably, the bootstrap CSS defines h1 already as well. You therefore need to change the order of the CSS files in your HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/style.css" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
Adding only !important to your CSS does not solve the issue.

Polymer and NodeJs/ Express server

I am using Polymer combined with a NodeJs/Express server which I am planning on hosting with Firebase functions.
My problem here is that besides the index.html none of the inner files can be found (404). With none of them I am revering to the first imports made inside my index file.(webcomponents-loader.js and the my-app.html)
I tried many different flavours. From absolute paths, with base tag and without and with a different directory structure.
I am clearly not an expert when it comes to node.js or express so I believe I am doing something fundamentally wrong.
Update
The links that can't be found have a different URL then the path that serves my index.html
404: http://localhost:5000/src/my-app.html
index: http://localhost:5000/nodefire-96b46/us-central1/serve
My directory:
fire_node
functions
node_modules
index.js
build
modern
bower_components
index.html
polymer.json
src
my-app
My server file
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/build/modern'));
app.get('/', (req, res) => {
res.sendFile("index.html", {root: '.'});
});
app.listen(2000, () => {
console.log('Server is listening on port 2000');
});
My index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>My App</title>
<base href="/modern/">
<link rel="manifest" href="manifest.json">
<script>
window.Polymer = { rootPath: '/' };
</script>
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
<link rel="import" href="http://localhost:4000/fire_node/functions/build/modern/src/my-app.html">
</head>
<body>
<my-app></my-app>
<noscript>
Please enable JavaScript to view this website..
</noscript>
</body>
</html>

How to add styles(css) and js to handlebar files?

I want to add styles and js to my handlebar files. I tried looking for different places but still not able to find a solution. I tried using partials to store the stylesheet tags then adding those partials to handlebar but that too didn't worked.
(Or if there is any other templating engine that provides much better css support, that too will work for me)
Please Help!
styles.hbs (partial file)
<link rel="stylesheet" href="./../css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./../css/main.css">
server.js
const express = require('express');
const hbs = require('hbs');
var app = express();
app.set('view engine', 'hbs');
hbs.registerPartials(__dirname + '/views/partials');
app.get('/', (req, res) => {
res.render('index.hbs');
});
app.listen(3000, ()=>{
console.log('Server is up at port 3000');
});
index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Home Page</title>
{{> styles}}
</head>
<body>
...
</body>
</html>
This is an old question but still confusing. Here is the most effective way to use different css file in your views:
main.hbs (Your base layout)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mainstyle.css">
<!-- mainstyle.css will be effective in all pages-->
{{{customstyle}}}
<title>{{title}}</title>
</head>
<body>
{{body}}
</body>
</html>
Please pay attention {{{customstyle}}} line in main.hbs
app.js
...
app.use((req, res) => {
res.status(404).render("404page", {title:"404 not found",
customstyle: `<link rel="stylesheet" href="/css/customstyle.css">`});
});
...
Thats it. As you know, {{{ }}} renders as html code, but {{ }} renders as only text in handlebars. customstyle passes as an argument to main.hbs layout file. We used three curly brackets in main.hbs file, because of we wanted to process the argument we send as html code. In this way, customsytle.css file added only when 404page viewed.

NodeJS and ExpressJS - Javascript files load but CSS files don't

I am building a web app using NodeJS, ExpressJS, AngularJS, Bootstrap, and a Postgres DB using Sequelize. I am having problems with loading all of my "asset" files when I load up my index.html page.
So here is my structure:
server.js
app
index.html
app.js
assets
css
styles.css
img
js
javascript files
Here is my server.js file:
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
var database = require('./config/database');
var path = require('path');
app.use(express.static(__dirname + '/app'));
require('./api/routes.js')(app);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.listen(port, function() {
console.log("Node app is running at localhost:" + port);
});
Here is my index.html file:
<DOCTYPE html>
<html lang='en' ng-app="app">
<head>
<link src='assets/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
<link src='assets/css/styles.css' rel='stylesheet' type='text/css' />
</head>
<body ng-controller="controller">
<nav class="navbar navbar-inverse navbar-fixed-top">
</nav>
<script src='assets/js/jquery-2.1.3.min.js'></script>
<script src='assets/js/angular.min.js'></script>
<script src='assets/js/angular-route.min.js'></script>
<script src='assets/js/angular-resource.min.js'></script>
<script src='assets/js/bootstrap.min.js'></script>
<script src='assets/js/modernizr.js'></script>
<script src='app.js'></script>
</body>
</html>
My problem is that, with my current setup, when I start up node and hit my localhost:5000 the index.html file loads along with all of my javascript files inside the assets/js folder. When I open up chrome dev tools I can actually see that folder being loaded in the sources pane. However, NONE of my CSS loads. Why is that? Any help would be greatly appreciated as I have basically exhausted all other options.
first post, so be generous. :)
you should actually use href to reference your css files.
<link href='assets/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
<link href='assets/css/styles.css' rel='stylesheet' type='text/css' />
See here: http://matthewjamestaylor.com/blog/adding-css-to-html-with-link-embed-inline-and-import

Categories

Resources