I am learning to use ejs, express, node js. I am having probling my style sheet to my header here is my code and here is a . I am using header and footer as include. Here is my
My app.js-
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.get("/", function(req, res) {
res.render("home");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
2 things to note here
style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.
In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image
it can be done by
app.use(express.static(__dirname + '/public'));
assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like
<link href="/css/style.css" rel="stylesheet" type="text/css">
Here i assume you have put the css file in css folder inside your public folder.
So folder structure would be
.
./app.js
./public
/css
/style.css
close head tag appropriately
I know similar questions have been asked before, but I've had a good look through & unfortunately none of the answers are helping me.
My CSS file is being ignored in certain circumstances.
So in my app.js file I have this code, defining my view engine setup
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
In my index.js file I have the following the code for UserList page
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db; // (1) Extract the db object we passed to our HTTP request
var collection = db.get('usercollection'); // (2) Tell our app which collection we want to use
// (3) Find (query) results are returned to the docs variable
collection.find({},{},function(e,docs){
res.render('userlist', { "userlist" : docs }); // (4) Render userlist by passing returend results to said variable
});
});
Finally, my userlist.ejs page looks like this:
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
<link rel='stylesheet' href='/stylesheets/style.css' type="text/css" />
</head>
<body>
<h1>User List</h1>
<ul>
<%
var list = '';
for (i = 0; i < userlist.length; i++) {
list += '<li>' + userlist[i].username + '</li>';
}
return list;
%>
</ul>
</body>
</html>
But when I run my page the CSS file is not loaded. However if I exclude this code:
<%
var list = '';
for (i = 0; i < userlist.length; i++) {
list += '<li>' + userlist[i].username + '</li>';
}
return list;
%>
The CSS file is loaded and applied without issue. Can anyone tell me why this is please? Apologies for the newbie question, but I've been trying to figure this out for ages.
I should mention the 'h1' tags are ignored too. The only thing rendered is the list items.
Not sure if its relevant, but my app is connecting to MongoDB to return the user data.
Any assistance would be very much appreciated!
Thank you!
Make sure that your CSS file is either defined as an endpoint in your index.js file or make sure that public/stylesheets/style.css exists so it can be loaded through the app.use(express.static(path.join(__dirname, 'public'))); command.
I am having trouble with serving a css file to the individual blog posts in the blog portion of my website.
So the way it works:
Go to /blog- you get the blog page and that works fine.
But when I am trying to get to, for example, /blog/post1 I am getting an error
http://localhost:4000/blog/static/css/style.css
I'd appreciate the help because I'm pretty new to express and routing files around and around. Cheers.
My file structure looks like this
blog
/node_modules
/src
/mock
/public
/css
style.css
/templates
/partials
_head.jade
_nav.jade
blog.jade
index.jade
layout.jade
post.jade
app.js
So the way it works:
Go to /blog- you get the blog page and that works fine.
But when I am trying to get to, for example, /blog/post1 I am getting an error
http://localhost:4000/blog/static/css/style.css
Here is what my respective files look like, maybe I'm missing something:
app.js
"use strict";
var express = require("express"),
posts = require("./mock/posts.json");
var postsLists = Object.keys(posts).map(function(value){
return posts[value]
});
var app = express();
app.use("/static", express.static(__dirname + "/public"))
app.set("view engine", "jade");
app.set("views", __dirname + "/templates");
app.get("/", function(req, res){
res.render("index");
});
app.get("/blog/:title?", function(req, res){
var title = req.params.title;
if (title === undefined) {
res.status(503);
res.render("blog", {posts: postsLists});
} else {
var post = posts[title] || {};
res.render("post", {post: post} );
}
});
app.get("/about", function(req, res){
res.send("<h1>About Page</h1>");
})
app.get("/projects", function(req, res){
res.send("<h1>Projects Page</h1>")
})
app.listen(4000, function(){
console.log("Frontend server is running on port 4000.")
});
_head.jade
head
meta(charset="UTF-8")
link(rel="stylesheet", href="static/css/style.css")
layout.jade
doctype html
html(lang="en")
include ./partials/_head.jade
body
block content
blog.jade
extends ./layout
block content
section(id="postHolder")
for post in posts
div.post
h2 #{post.title}
p #{post.body}
a(href="/blog/" + post.title)
button Read More
post.jade
extends ./layout.jade
block content
section
div.post
h2 #{post.title}
p #{post.body}
p This is the actual post page itself.
I guess doing this will get you there -
head
meta(charset="UTF-8")
link(rel="stylesheet", href="/css/style.css")
Okay so I want to draw your attention to my _head.jade file:
head
meta(charset="UTF-8")
link(rel="stylesheet", href="/static/css/style.css")
I needed to make a reference to the absolute path and add the "/" in front of "static"
It used to be static/css/style.css and now it's
/static/css/style.css I'm pretty new to this and I don't know if I explained the reference to the absolute path correctly.
I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can't get my styles.css to load.
From app.js
app.use(express.static(path.join(__dirname, 'public')));
In my .ejs, I have tried both of these lines
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/public/css/style.css" />
Neither loads the css. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.
My path looks like
.
./app.js
./public
/css
/style.css
Use this in your server.js file
app.use(express.static(__dirname + '/public'));
and add css like
<link rel="stylesheet" type="text/css" href="css/style.css" />
dont need / before css like
<link rel="stylesheet" type="text/css" href="/css/style.css" />
1.Create a new folder named 'public' if none exists.
2.Create a new folder named 'css' under the newly created 'public' folder
3.create your css file under the public/css path
4.On your html link css i.e
<link rel="stylesheet" type="text/css" href="/css/style.css">
// note the href uses a slash(/) before and you do not need to include the 'public'
5.On your app.js include :
app.use(express.static('public'));
Boom.It works!!
The custom style sheets that we have are static pages in our local file system. In order for server to serve static files, we have to use,
app.use(express.static("public"));
where,
public is a folder we have to create inside our root directory and it must have other folders like css, images.. etc
The directory structure would look like :
Then in your html file, refer to the style.css as
<link type="text/css" href="css/styles.css" rel="stylesheet">
For NodeJS I would get the file name from the res.url, write the header for the file by getting the extension of the file with path.extname, create a read stream for the file, and pipe the response.
const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
let filePath = path.join(
__dirname,
"public",
req.url === "/" ? "index.html" : req.url
);
let extName = path.extname(filePath);
let contentType = 'text/html';
switch (extName) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
}
console.log(`File path: ${filePath}`);
console.log(`Content-Type: ${contentType}`)
res.writeHead(200, {'Content-Type': contentType});
const readStream = fs.createReadStream(filePath);
readStream.pipe(res);
});
server.listen(port, (err) => {
if (err) {
console.log(`Error: ${err}`)
} else {
console.log(`Server listening at port ${port}...`);
}
});
Use in your main .js file:
app.use('/css',express.static(__dirname +'/css'));
use in you main .html file:
<link rel="stylesheet" type="text/css" href="css/style.css" />
The reason you getting an error because you are using a comma instead of a concat + after __dirname.
In your app or server.js file include this line:
app.use(express.static('public'));
In your index.ejs, following line will help you:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
I hope this helps, it did for me!
IMHO answering this question with the use of ExpressJS is to give a superficial answer. I am going to answer the best I can with out the use of any frameworks or modules. The reason this question is often answerd with the use of a framework is becuase it takes away the requirment of understanding 'Hypertext-Transfer-Protocall'.
The first thing that should be pointed out is that this is more a problem surrounding "Hypertext-Transfer-Protocol" than it is Javascript. When request are made the url is sent, aswell as the content-type that is expected.
The second thing to understand is where request come from. Iitialy a person will request a HTML document, but depending on what is written inside the document, the document itsself might make requests of the server, such as: Images, stylesheets and more. This question refers to CSS so we will keep our focus there. In a tag that links a CSS file to an HTML file there are 3 properties. rel="stylesheet" type="text/css" and href="http://localhost/..." for this example we are going to focus on type and href. Type sends a request to the server that lets the server know it is requesting 'text/css', and 'href' is telling it where the request is being made too.
so with that pointed out we now know what information is being sent to the server now we can now seperate css request from html request on our serverside using a bit of javascript.
var http = require('http');
var url = require('url');
var fs = require('fs');
function onRequest(request, response){
if(request.headers.accept.split(',')[0] == 'text/css') {
console.log('TRUE');
fs.readFile('index.css', (err, data)=>{
response.writeHeader(200, {'Content-Type': 'text/css'});
response.write(data);
response.end();
});
}
else {
console.log('FALSE');
fs.readFile('index.html', function(err, data){
response.writeHead(200, {'Content_type': 'text/html'});
response.write(data);
response.end();
});
};
};
http.createServer(onRequest).listen(8888);
console.log('[SERVER] - Started!');
Here is a quick sample of one way I might seperate request. Now remember this is a quick example that would typically be split accross severfiles, some of which would have functions as dependancys to others, but for the sack of 'all in a nutshell' this is the best I could do. I tested it and it worked. Remember that index.css and index.html can be swapped with any html/css files you want.
I have used the following steps to resolve this problem
create new folder (static) and move all js and css file into this folder.
then add app.use('/static', express.static('static'))
add css like <link rel="stylesheet" type="text/css" href="/static/style.css"/>
restart server to view impact after changes.
Use this in your server.js file
app.use(express.static('public'));
without the directory ( __dirname ) and then within your project folder create a new file and name it public then put all your static files inside it
Its simple if you are using express.static(__dirname + 'public') then don't forget to put a forward slash before public that is express.static(__dirname + '/public') or use express.static('public') its also going to work;
and don't change anything in CSS linking.
the order of registering routes is important . register 404 routes after static files.
correct order:
app.use("/admin", admin);
...
app.use(express.static(join(__dirname, "public")));
app.use((req, res) => {
res.status(404);
res.send("404");
});
otherwise everything which is not in routes , like css files etc.. , will become 404 .
The above responses half worked and I'm not why they didn't on my machine but I had to do the following for it work.
Created a directory at the root
/public/js/
Paste this into your server.js file with name matching the name of directory created above. Note adding /public as the first param
app.use('/public',express.static('public'));
Finally in the HTML page to which to import the javascript file into,
<script src="public/js/bundle.js"></script>
I have a website that uses classic ASP to render settings for CKEditor 3.
On the serverside I have:
<%
Dim Editor
Set Editor = New CKEditor
Editor.basePath = "/ckeditor/"
Editor.Config("contentsCss") = "/Styles/Editor.css"
Editor.Config("templates_files") = "/templates/news.js"
Editor.Config("width") = 570;
Editor.editor "Html", Html
Set Editor = Nothing
%>
And in news.js I have:
CKEDITOR.addTemplates('news',
{
imagesPath: CKEDITOR.getUrl('/JavaScripts/ckeditor_3.6.3/templates/images/'),
templates:
[
{
title: 'News Template',
//image: 'template1.gif',
html:
'<h3>Template 2</h3>' +
'<p>Type your text here.</p>'
}
]
});
And it renders:
<script type="text/javascript" src="/ckeditor/ckeditor.js?t=C3HA5RM"></script>
<script type="text/javascript">//<![CDATA[
CKEDITOR.replace('Html', {"contentsCss": "\u002FStyles\u002FEditor.css","templates_files": "\u002Ftemplates\u002Fnews.js","width": 570});
//]]></script>
It seems like it takes the path provided (/templates)... and does a 404 with each letter from it.... i.e /t /e /m ...
What might be missing?
According to the documentation, the templates_files should be an array of strings, even if you use only one file, so the correct configuration is
Editor.Config("templates_files") = Array("/templates/news.js")