Node.js Undefined CSS file - javascript

I just created a default Node.js Express Project. The index.ejs file is giving me the error:
Undefined CSS file ('/stylesheets/style.css').
Here is the index.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
Here is what I think is the relevant code from the app.js file:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
The directory structure looks like this:
To my understanding, app.use(express.static(path.join(__dirname, 'public'))); should allow me to reference the relative directory <link rel='stylesheet' href='/stylesheets/style.css' />, but I am still getting the undefined css error. What is wrong?
EDIT: Here is my current configuration:
app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('public', __dirname + '/public');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static('public'));
// development only
if ('development' == app.get('env')) { // jshint ignore:line
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/', function(req, res){ res.render('index.ejs'); });
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
index.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>

Try
app.use(express.static(path.join(__dirname, '/public')));
or
app.use(express.static('public'));
Express documentation here
Edit 1:
You have an extra '/'
<link rel='stylesheet' href='stylesheets/style.css' />

This seems to be an eclipse bug. The style.css is actually being read by the page in spite of the error showing in index.ejs.

Related

CSS seems to be sent to page, but nothing applies [ExpressJS + Handlebars]

I am attempting to do a very simple page with Handlebars and Express with NodeJS, however I am running into difficulty getting it to display css. It seems that the browser is receiving the CSS file given the feedback and the 200 code I'm getting in my Node window, but no effect is shown on the actual page.
file structure
app.js
/public
/stylesheets
style.css
/views
/layouts
main.handlebars
home.handlebars
app.js
var express = require('express');
var exphbs = require('express-handlebars');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
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')));
var person = {
name:"Clay",
age:"20",
attr:["tall","handsome","wearing a red sweater"]
}
app.get('/', function (req, res, next) {
res.render('home', {layout: false, people: person});
});
module.exports = app;
main.handlebars
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Database</title>
<link rel="stylesheet" href="stylesheets/style.css" />
</head>
<body>
{{{body}}}
</body>
</html>
home.handlebars
<h1>Example App: Home</h1>
hello world
style.css
body {
background-color: red;
}
node console

How to Solve The partial head could not be found Handlebars

I run ExpressJS and installed Handlebars as a template engine. I'm using AdminLTE and split it up to 6 hbs files in /views/layouts. I put AdminLTE template in public folder.
views/layouts
-- base.hbs // as defaultLayout
-- footer.hbs
-- head.hbs
-- js.hbs
-- nav.hbs
-- sidebar.hbs
I get the following error on node console everytime when i try to access localhost:3000
Error: The partial head could not be found
Here is my app.js setup:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var mongoose = require('mongoose');
var validator = require('express-validator');
var override = require('method-override');
var hbs = require('express-handlebars');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'base', layoutDir: __dirname + '/views/layouts'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({secret: "1234"}));
app.use(flash());
app.use(validator());
app.use(override(function(req, res) {
if (req.body && typeof req.body == 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}
}));
[...]
And this is my base.hbs file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
{{> head}}
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
{{> nav}}
{{> sidebar}}
<div class="content-wrapper">
{{{ body }}}
</div>
{{> footer}}
<div class="control-sidebar-bg"></div>
{{> js}}
</div>
</body>
</html>
You need to register the path to partials directory while configuring express-handlebars and move your partials to that folder.
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'base',
layoutsDir: path.join(__dirname, 'views/layouts'),
partialsDir : [
// path to your partials
path.join(__dirname, 'views/partials'),
]
}));
[const hbs = require('hbs');
//this required before view engine setup
hbs.registerPartials(__dirname + '/views/partials');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
]1
use in app.js/index.js
hbs.registerPartials(__dirname + '/views/layouts');
use proper syntax in template hbs files Example: {{> header}}
I have fixed the issue by providing the id in HTML DOM. This part I missed in html.
<div class="modal-footer" id="btn-group"></div>
This is my js part
var templateBtnGroup = Handlebars.getTemplate("btn-group", "btn-group.html");
Handlebars.registerPartial("btn-group", templateBtnGroup());
var templateBtnGroupScript = Handlebars.compile($('#handlebars-btn-group').html());
$("#btn-group").append(templateBtnGroupScript());
Please check the folder names case. "Public" folder may present and you are referring to lowercase "public" will not render the css/images/client side js
You should create a subfolder for partials, and after that point to that folder with partialsDir:
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'base',
layoutDir: __dirname + '/views/layouts',
partialsDir: path.join(__dirname, 'views/partials'),
}));
Make sure to use
extName to extname in viewEngine object for partials
var options = {
viewEngine: {
extname: '.hbs',
layoutsDir: 'views/layouts/',
defaultLayout : 'template.hbs',
partialsDir : 'views/partials/'
},
viewPath: 'views/emails/',
extName: '.hbs'
};
Directory
=> views/layouts/template.hbs
=> views/emails/forgot-password.hbs
=> views/partials/header.hbs
/footer.hbs
In template.hbs
<html>
<body>
<div class="container">
{{>header}}
{{{body}}}
{{>footer}}
</div>
</body>
</html>

Unable to load js and css files in node.js

This is html page.I'm calling this page from node.js server i.e, app.js.Here I'm unable to load socket.io.js,bootstrap.js,bootstrap.css pages.
My index.html:
<html>
<script type="text/javascript" src="/javascripts/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type ="text/javascript" src="/javascripts/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.css" />
<div id="progressbar">
</div>
<script>
var socket = io('http://localhost:8085');
socket.on('connect', function(){});
socket.on('message', function(data){
$('#progressbar').progressbar({
maximum: 100,
step: JSON.parse(data).percent
});
});
socket.on('disconnect', function(){});
</script>
</html>
My app.js code :
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
//res.send('Hello World!');
});
In firebug,I'm facing this
You have set up incorrect paths for static files.
In your case, you'll need to use this:
app.use('/javascripts', express.static(__dirname + '/javascripts'));
app.use('/stylesheets', express.static(__dirname + '/stylesheets'));
Now, whatever files are in javascripts and stylesheets folders will load as static files.
Your current method of using static files:
app.use(express.static(path.join(__dirname, 'public')));
This will load everything that's beneath public folder as static files, so you would need to move the javascripts and stylesheets folders there if you want that to work.
change your view engine to html and modify the code like below :
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'html');
and change the sendfile method :
res.sendFile(path.join(__dirname, '../YOUR_FOLDER_NAME/public', 'index.html'));
EDITED::
change the index.html file:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheets/test.css" />
This is the app.js. (based on #Andrius' solution) I was able to make it running on http://localhost:8085. index.html stays the same.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//test
app.use('/javascripts', express.static(__dirname + '/javascripts'));
app.use('/stylesheets', express.static(__dirname + '/stylesheets'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', routes);
//app.use('/users', users);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
//res.send('Hello World!');
});

ExpressJS + AngularJS single page without template not found page (404)

My application does not load templates in ng-view inside the index.thml.
I let my code here because i am lost.
app.js
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
// var $ = require('jquery');
// global.jQuery = $;
// var bootstrap = require('bootstrap');
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + 'views');
app.set('view engine', 'html');
var routes = require('./routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Started Success http://localhost:' + server.address().port);
});
And angular route
angular.module('geradorContrato', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/contrato', {
templateUrl: '/public/views/contrato.html',
controller: 'ContratoController'
})
.when('/contratante', {
templateUrl: '/public/views/contratante.html',
controller: 'ContratanteController'
})
.when('/contratada', {
templateUrl: '/public/views/contratada.html',
controller: 'ContratadaController'
})
.when('/bemvindo', {
templateUrl: 'public/views/bemVindo.html',
});
});
But when i access http://localhost:3000/#/bemvindo
The page index.html loading success, but ngview not load and showing the message Cannot GET /public/views/bemVindo.html into console network chrome
Below is my index.html
<!DOCTYPE html>
<html ng-app="geradorContrato">
<head>
<meta charset="UTF-8">
<base href="/">
<link rel='stylesheet' href='/stylesheets/dist/css/bootstrap-theme.css'>
<link rel='stylesheet' href='/stylesheets/dist/css/bootstrap.css'>
<link rel="stylesheet" type="text/css" href="/stylesheets/mainStyle.css">
<script src="/javascript/lib/angular.js"></script>
<script src="/javascript/lib/angular-route.js"></script>
<script src="/javascript/lib/jquery.js"></script>
<script src="/javascript/lib/bootstrap.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="/javascript/main.js"></script>
<script src="/javascript/ContratoController.js"></script>
<title>Cadastro</title>
<head>
<body>
<div class="container">
<ng-view></ng-view>
</div>
</body>
</html>
and below is my page simple bemVindo.html
OLÁ SEJA VEM VINDO!
This is base structure my app
Structure
Sorry guys, if you do not understand something tell me pl
sorry for my english
Suggestions
deek:
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'public')));
var routes = require('./routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', express.static(path.join(__dirname, '/public/views/index.html')));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Started Success http://localhost:' + server.address().port);
});
Error Cannot GET /
path you have given must be wrong, check for the path where your file resides, try to console the path in the javascript console and provide the right path. "Cannot GET /public/views/bemVindo.html" means that the file bemVindo.html is not in the folder /public/views. It is not able to find the file hence showing this error.
Get rid of :
app.set('views', __dirname + 'views');
app.set('view engine', 'html');
Not needed....view engine html is default. Views folder isn't used.
EDIT: remove this too:
app.use(express.static(path.join(__dirname, 'public')));
Change this:
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
To this:
app.use('/', express.static(path.join(__dirname, '/public/views/index.html')));
Let's express know this is a static directory where the html and supporting files are.
Express will treat it like a normal html directory and try to find an index file. From your index file, the angular will take over routing.
If you wanted to utilize express and templates for routing, the way you did it is best.
You set views folder if you want express to load template files from it but you have none.
You can mix and match with angular too.

SyntaxError: Unexpected token : in D:\practise\nodejs\nodejs-demo\views\index.html while compiling ejs

I try to change the engne view from .ejs to .html something goes wrong ! after search the net, I don't find the answer. here are the problems :
like this:
Express
500 SyntaxError: Unexpected token : in D:\practise\nodejs\nodejs-demo\views\index.html while compiling ejs
at Function (native)
at Object.Template.compile (D:\practise\nodejs\nodejs-demo\node_modules\ejs\lib\ejs.js:455:12)
at Object.compile (D:\practise\nodejs\nodejs-demo\node_modules\ejs\lib\ejs.js:288:16)
at handleCache (D:\practise\nodejs\nodejs-demo\node_modules\ejs\lib\ejs.js:147:16)
at View.exports.renderFile [as engine] (D:\practise\nodejs\nodejs-demo\node_modules\ejs\lib\ejs.js:348:14)
at View.render (D:\practise\nodejs\nodejs-demo\node_modules\express\lib\view.js:76:8)
at Function.app.render (D:\practise\nodejs\nodejs-demo\node_modules\express\lib\application.js:561:10)
at ServerResponse.res.render (D:\practise\nodejs\nodejs-demo\node_modules\express\lib\response.js:845:7)
at exports.index (D:\practise\nodejs\nodejs-demo\routes\index.js:7:7)
at callbacks (D:\practise\nodejs\nodejs-demo\node_modules\express\lib\router\index.js:164:37)
here are some file content:
app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var ejs = require('ejs');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
//使用html 扩展
app.engine('.html',ejs.__express);
app.set('view engine','html');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%=: title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<!-- Bootstrap -->
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css" media="screen">
<!-- <link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen"> -->
</head>
<body screen_capture_injected="true">
footer.html
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
index.html
<!-header-->
<% include header.html %>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<% include footer.html %>
environment
node v0.12.2 npm 2.7.4 express 3.20.2
The error message says you have an unexpected token (a colon) in index.html. You have this:
<%=: title %>
Remove the colon.

Categories

Resources