Unable to load js and css files in node.js - javascript

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!');
});

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

Express - Not able to use multiple static folders for different routes

I'm trying to show 2 different Angular 2 apps through Node/Express route.
But my route only shows only the root's index.html even on the path of other route. I tried a lot of different things but nothing seem to work. Would appreciate any help in this.
UPDATE:
I solved the problem by replacing these codes in server.js:
But now the issue is my route url shows like this "http://localhost:3020/iot/#./". I changed the LocationStrategy from HashLocationStrategy to PathLocationStrategy in app.module.ts but then the route doesn't work. How do I remove the '#' tags from my urls. If any one could suggest.
Hope my answer would help someone facing the same problem.
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use('/', express.static(path.join(__dirname,'/client/dist/')));
app.use('/mwc', express.static(path.join(__dirname,'/mwc/dist/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', index);
app.use('/mwc', mwc);
app.use('/api/vi/', todos);
with just this
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', express.static('client/dist'));
app.use('/mwc', express.static('mwc/dist'));
app.use('/iot', express.static('iot/dist'));
app.use('/canteen', express.static('canteen/dist'));
app.use('/api/vi/', todos);
& including the following code in my angular apps 'app.module.ts' & changing base href from "/" to "./" in index.html file.
import { CommonModule, APP_BASE_HREF, LocationStrategy, HashLocationStrategy} from '#angular/common';
providers: [
{ provide: APP_BASE_HREF, useValue: './' },
{ provide: LocationStrategy, useClass: HashLocationStrategy }
],
Below is the previous code:
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var todos = require('./routes/todos');
var mwc = require('./routes/mwc');
var app = express();
var router = express.Router();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use('/', express.static(path.join(__dirname,'/client/dist/')));
app.use('/mwc', express.static(path.join(__dirname,'/mwc/dist/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', index);
app.use('/mwc', mwc);
app.use('/api/vi/', todos);
app.listen(3020, function(){
console.log("Server started on port 3020...");
});

Node.js Undefined CSS file

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.

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.

Adding subdomain in nodejs and express

I am trying to add in a subdomain with node.sj and Expressjs v3, but I keep getting 404 cannot get / when trying to load the subdomain.
var express = require('express'),
app = module.exports = express(),
MongoStore = require('connect-mongodb'),
server = require('http').createServer(app),
fs = require('fs'),
socket = require('./lib/sockets'),
flash = require('./middleware/flash');
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
app.configure(function () {
app.use(express.favicon(__dirname + '/public/domain.com/images/favicon.ico'));
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views/site');
app.set('view engine', 'ejs');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(flash());
app.use(app.router);
app.use(express.vhost(app.get('manager_vhost'), require('./subdomains/Manager')));
});
server.listen(3000);
socket.listen(server, sessionStore, app);
This is what I have in my Manager file
var express = require('express'),
manager = module.exports = express();
manager.configure(function () {
manager.use(express.static(manager.get('base_location') + '/public/'));
manager.engine('.html', require('ejs').__express);
manager.set('view engine', 'ejs');
manager.set('version', version);
});
Is there something I am doing wrong here?
Where are your routes defined? Try adding in a route and see what happens
manager.get('/', function (req, res) {
res.render('layout', {
title: 'Manager '
});
});

Categories

Resources