Can't get stylesheet to work with ejs for node.js - node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.

Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />

in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />

Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>

To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.

With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Related

NodeJS: Stylesheet not loading due to unsupported mime type

I'm making an app with NodeJS and Express, and when I start the server I get the following error:
Refused to apply style from 'http://localhost:3000/style.css' because its MIME type
('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Here's my directory tree:
app:
|-node-modules
|-index.js
|-package.json
|-package-lock.json
|-views
|-index.html
|-public
|-stylesheets
|-style.css
Here's my index.js:
const express = require("express");
const app = express();
const path = require("path");
app.use("/static", express.static(__dirname + "/public"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/views/index.html"));
});
app.listen(process.env.port || 3000);
console.log("Server Is Active At Port " + (process.env.port || 3000));
And here's my index.html and style.css:
<!DOCTYPE html>
<html>
<head>
<title>Express App</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="/public/stylesheets/style.css">
</head>
<body>
<h1>Test</h1>
</body>
</html>
body{
text-align: center;
}
Please note that I'm just testing to see if the site works, and this isn't the full code for the site.
You're not showing us the full picture - how are your styles being loaded? Presumably with a <link> tag you opted not to show us. Anyhow, the express.static middleware should take care of setting the correct mime type. You probably aren't providing the correct path to the stylesheet.
Your style tag in your html should look something like this:
<!-- note the "/static" part at the beginning of the url -->
<link rel="stylesheet" href="/static/stylesheets/style.css" />
Try writing
app.use('/public' , express.static(path.join(__dirname, 'public'))); instead of app.use("/static", express.static(__dirname + "/public"));
After that in your html while linking to the css file you can write
<link rel="stylesheet" href="/public/stylesheets/style.css">
Hope this solves the issue
I think this will work. Define path like this:
const staticfiledir = path.join(__dirname,'../public')
Setup for static directories to serve
app.use(express.static(staticfiledir))

Express only serving css file in main page

I am learning node and using expressjs the problem is that the css file is only working on the main page and not any other page following is the code for the app:
var express = require("express");
var app = express();
// assets
app.use(express.static("public"));
// simple file testing
app.get("/anything/:stuff", function(req, res){
var stuff = req.params.stuff;
res.render("love.ejs", {stuff: stuff});
});
// posts page
var books = [
{title:"Harry Potter",author:"JK Rowling",editions:7},
{title:"Peere Kamil",author:"Humaira Saeed",editions:4},
{title:"Mushaf",author:"Abdullah khan",editions:2}
];
app.get("/books", function(req, res){
res.render("books.ejs",{books:books});
});
app.listen(3000, process.env.IP, function(){
console.log("Serving Now!");
});
The following is the code for the page where it is not working.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="app.css" />
<title>demo app</title>
</head>
<body>
<h1>You fell in love with : <%= stuff %> </h1>
<%
if(stuff.toUpperCase() === "WAQAS"){ %>
<P>GOOD CHOICE HE IS THE BEST</p>
<% } %>
<p>P.S This is the love.ejs file</p>
</body>
</html>
The file is under public directory.
Use an absolute URL for the CSS file, so the browser doesn't look for it relative to the current URL:
<link rel="stylesheet" href="/app.css" />
Explanation: say that you open the URL /anything/helloworld in your browser. When your HTML contains just app.css, without the leading slash in front of it, the browser will try and load /anything/app.css (because without that slash it's relative to the current URL), which doesn't point to your CSS file.
When you add the leading slash, express.static will be able to find the CSS file in public/.

Nodejs Express - Why won't my static file be served?

Ive been looking a all kind of posts and just can't understand my mistake. Whatever I do, my css file is just not being served.Does anyone know why?
test/server/app.js:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'browser')));
var PORT = process.env.PORT || 1337;
app.listen(PORT, function() {
console.log('Server is listening!');
});
test/browser/index.html:
<head>
<base href="/" />
<title>Test</title>
<link rel="stylesheet" type="text/css" href="public/style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
<script src="js/app.controller.js"></script>
</head>
<body>
<p>hello world</p>
</body>
</html>
My css file is in test/public/style.css
Your app code can be found in test/server/, which means that path.join(__dirname, 'public') will yield (the absolute path value for) test/server/public, which is not where your CSS file is located.
Instead, you'd want to use this:
path.join(__dirname, '..', 'public')`
Which would make it point to test/public/.
However, this only partly solved the problem, because you're also telling Express that test/public/ is the root directory of the static resources, meaning that your stylesheet's URL is /style.css, not public/style.css.
If you want to keep the public prefix (which you probably do), you need to use this:
app.use('/public', express.static(path.join(__dirname, '..', 'public')));
And in your HTML, be sure to use absolute paths:
<link rel="stylesheet" type="text/css" href="/public/style.css" />

Cannot load stylesheets node

I have created basic node/express server
var express = require('express');
var app = express();
var path = require('path')
var port = 8080;
app.use("/styles", express.static('../public/styles'));
app.get('/' , function( req , res ){
console.log(__dirname)
res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)
structure of project is simple
app
public
html
index.html
styles
javascripts
routes
server.js
html file looks very simple
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../styles/index.css">
<title> Hello world!</title>
</head>
<body>
</body>
</html>
yet it still complains
GET http://localhost:8080/index.css 404 (Not Found)
Yet my paths should be correct , i looked up this problem and every answer is about using
app.use("/styles", express.static('../public/styles'));
so browser know how to redirect when looking for a stylesheets. Which does not work for me.
Could anybody help with this common problem?
Thanks!
Not clear what your project structure is. It's more common to have app.js in your project directory contain the basic express server and if you have complicated routing, do that in routes/server.js
So you could change your project structure:
app.js (main file)
public
index.html
styles
index.css
javascripts
routes
server.js --not needed?
If that's the case, change app.js to:
var express = require('express');
var app = express();
var port = 8080;
//use static folder public to serve everything up
app.use(express.static('./public/'));
app.listen(port)
In index.html, to include index.css:
<link rel="stylesheet" href="/styles/index.css" >

Express & EJS - layout.ejs not used

Im trying out EJS as a view engine with Express. It seems that my layout.ejs is not used. I have two views index.ejs and layout.ejs both in my 'views' folder. It seems that index.js is rendered but layout.ejs is not. The layout.ejs file should be including a CSS file but when the page is rendered in the browser this is not there. Any test test text that I place in the layout.ejs file is not output with the response.
Am I missing an additional configuration step?
Thanks!
My server.js code:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs', {title: 'EJS Engine'});
});
app.listen(8080);
In my layout.ejs I am linking to a single css file which resides in the public folder.
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<%- body %>
</body>
</html>
index.ejs
<div id="container">
index.html
</div>
Here's the module you need:
https://www.npmjs.org/package/express-ejs-layouts
Do the following:
npm install express-ejs-layouts // install the layout module from the command line
var express = require("express")
,path = require('path')
,fs = require('fs')
,expressLayouts=require("express-ejs-layouts") // add this requirement
, app = express();
app.use(express.bodyParser());
app.use(expressLayouts); // add this use()
app.use(express.static(__dirname));
Now the ejs engine should use your layout.
app.set('view options', { layout:'layout.ejs' });
Place layout.ejs into your views folder.
Alternately you can place layout.ejs into views/layouts folder and then use
app.set('view options', { layout:'layouts/layout.ejs' });
I have a similar issue. In my case I would rather use Jade but I have a requirement for a more "html" style template engine for a particular project. At first I considered express-partials or ejs-locals (as mentioned in a comment by Jonathan Lonowski) or even using html via the pipe or dot syntax within Jade templates (see here for more information about that option and this SO post). I am not able to introduce the additional dependencies for express-partials and ejs-locals into this project. These two projects do look good and might meet your needs.
If you do not want to use these projects, you can do something like the following:
views/layout-head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>
views/layout-foot.ejs
</body>
</html>
views/index.ejs (or any other page)
<% include layout-head %>
This is the index page - <%= title %>
<% include layout-foot %>
routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
}
This is not an optimal solution but it works. Most of my application will be a single page app and I have some other restrictions I have to work within so this works for my needs. This may not the best solution in many cases - especially if you have complex and/or changing layouts.

Resources