Scripts and css files not loading with jade + node js - node.js

I am learning mean stack development. I am using working out with some examples. I am trying to load my css files and javascript files in the jade file. files are appearing in the console --> Sources. But all the css files are loading with empty data and all the js files are loading with html data.
I am having my server.js like this
var express = require("express");
var stylus = require("stylus");
var logger = require("morgan");
var bodyParser = require("body-parser");
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
function compile(str,path) {
return stylus(str).set('filename', path);
}
app.set('views', __dirname + '/server/views');
app.set('view_engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(stylus.middleware({
src: __dirname + '/public',
compile:compile
}));
//defining routes
app.get('*', function (req,res) {
res.render('index.jade');
});
var port = 3030;
app.listen(port);
console.log('starting listening....');
How to load the files properly in this scenario?

The requests for client side resources are not being handled by anything in your app, which means they get handled by your "catch-all" handler (app.get('*', ...)), which returns HTML (which explains why you are seeing HTML being returned for jQuery, for instance).
You want to use a static file handler in your app to handle those requests:
app.use(express.static(__dirname));
The __dirname argument points to the directory that holds your client side resources files, so you may need to change this.
Also, make sure that you add this line above your catch-all handler, otherwise the requests will still be handled by that instead of the static file handler.

Related

Run HTML file on HTTPS local server [duplicate]

I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })

How to serve static files using both express and ejs and send the data?

I am trying to serve files with express and send data to an html file using ejs. The problem is that I only have to use either express to serve the files or ejs to send data but for some reason I cant use both. My paths are right but probably I have to do something different to make both work. My code doesnt reach app.get when I use app.use(express.static('../dist')), but when I comment that line it does send the data. If I can know what is happening that would be great.
My code is the following:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('../dist'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname, '../dist');
app.listen(4000, function() { console.log('listening')});
let views;
jwt.authorize((err, response) => {
google.analytics('v3').data.ga.get(
{
auth: jwt,
ids: 'ga:' + view_id,
'start-date': '30daysAgo',
'end-date': 'today',
metrics: 'ga:sessions, ga:pageviews'
},
(err, result) => {
console.log();
views = result;
console.log(views.data.rows[0][0]);
app.get('/', function(req, res){
console.log('test');
res.render('../dist/index.html',{sessions:views.data.rows[0][0], pageviews:views.data.rows[0][1]});
});
}
);
});
If two routes match one URL, then whichever route is defined first will be used.
/ hits the static route, finds a match (with an index.html file) and serves it up.
The route matching code never gets as far as app.get('/'.
EJS files are not static files. Don't mix them together with your static files.
If there isn't an index.html in the directory you keep your static files in, then it won't match on the static route, so the route matching code will reach app.get('/'.
You should probably separate the files (into static and templates rather then lumping them together in dist) and make it clear which files are EJS templates by giving them .ejs file extensions instead of .html.

Node.js Serve-static not working

I'm having some trouble with routing and serving static files.
My directory structure is like this:
app/
--app.js
—-public/
—-js/
—-main.js
—-views/
—-pages/
—-index.jade
This is how I've set up my server:
app.js
var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
var publicPath = path.join(__dirname,'..','public');
var port = process.env.PORT || 3000
var app = express()
app.set('views', './views/pages')
app.set('view engine', 'jade')
app.use('/public', serveStatic(publicPath));
app.listen(port)
console.log("port is " + port)
app.get('/', function(req, res) {
res.render('index', {
title: 'index',
})
})
index.jade
doctype
html
head
meta(charset="utf-8")
title index
script(src="/public/js/main.js”)
body
h1=title
But this is what happens when I visit the index:
GET http://localhost:3000/public/js/main.js 404 (Not Found)
How do I set up the "serve-static" part to work?
Thanks!
you are passing the wrong parameter to it.
correct example for serving static files from different directory would be
This example shows a simple way to search through multiple directories. Files are look for in public-optimized/ first, then public/ second as a fallback.
var express = require('express')
var serveStatic = require('serve-static')
var app = express()
app.use(serveStatic(__dirname + '/public-optimized'))
app.use(serveStatic(__dirname + '/public'))
app.listen(3000)
check out the docs for more options https://github.com/expressjs/serve-static
I think you need to remove public from the path.
script(src="/js/main.js”)
You're telling the server static resources are served from the public folder.

Angular2 application with NodeJS not loading everything

I'm experimenting with Angular2 and, with the quick start guide on their official documentation, I'm definitely up and running. However, if I want to do any APIs on the server or host it on the cloud it seems I'll need to use Node. I think I have everything set correctly in the server.js file, yet when I run it it seems like it's not loading everything from SystemJS and I get the following errors:
Here is the Node code:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var System = require('systemjs');
// loads './app.js' from the current directory
System.import('app').then(function(m) {
console.log(m);
});
// Config
app.set('port', (process.env.PORT || 3000));
app.use('/app', express.static(__dirname + '/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(app.get('port'), function() {
console.log('MEAN app listening on port ' + app.get('port'));
});
app.get('*', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
I'm not sure what I'm missing to include in the Node side that gets included when running lite-server from npm start that is included from the Angular2 quick start guide.
When you are telling express where to look for the static files, you have to include where your js files will be as well.
For example, in one of my projects I have it like so
app.use('/css', express.static(path.resolve(appPath, 'css')));
app.use('/lib/css', express.static(path.resolve(appPath + '/lib', 'css')));
app.use('/lib/js', express.static(path.resolve(appPath + '/lib', 'js')));
app.use('/assets', express.static(path.resolve(appPath, 'assets')));
app.use('/node_modules', express.static(path.resolve(appPath, 'node_modules')));
app.use('/app', express.static(path.resolve(appPath, 'app')));
I believe that might be your issue or hopefully set you in the right path.

How to set the views variables in a Node.js+Express vertical structure project?

I decided to adopt a vertical structure for my Node.js+Express project, as a consequence I have sub-projects/sub-folders (User management, Cart, Inventory) by feature:
Project
--core
----views
----(...)
--usermgmt
----views
and obviously controllers, routes, models and views are defined for every feature.
My problem now is how to set the views directory for the project. I mean when I do that in horizontal structure, I write:
app.set('views', path.join(__dirname, 'views'));
It is easy since the views directory is unique
but now, I have many views directories so I don't know what the best practice is. For the moment, I set the variable views to __dirname and when I render I go from the root directory to the corresponding one.
Any advice?
I'd quote from the documentation itself.
A directory or an array of directories for the application's views. If
an array, the views are looked up in the order they occur in the
array.
http://expressjs.com/en/4x/api.html#app.set
(Scroll down and find views in table just below)
OR
You can create each of your feature as separate app (just don't do app.listen) then in your master app you can do something like this
Launch.js
#!/usr/bin/env node
var http = require('http');
var app = require('express')();
app.use('/feature1',require('./feature1');
app.use('/feature2',require('./feature2');
// Setup port
var port = process.env.PORT || 3000;
app.set('port', port);
//Create HTTP server.
var server = http.createServer(app);
//Listen on provided port, on all network interfaces.
server.listen(port);
server.on('listening', function(){
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
//You can open browser -- uncomment below line
//require("openurl").open("http://localhost:3000");
debug('Magic happens at : http://localhost:' + addr.port);
});
Your feature directories would contain an index.js which would do ...
.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var settings = require('./lib/settings');
//Import your routes
var defRoute = require('./defRoute');
var users = require('./users');
var someOtherResource = require('./someOtherResource');
var app = express();
// view engine setup
//This sets view for `this` app to relative `views` folder
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')));
//Mount your routes
app.use('/',defRoute);
app.use('/users', users);
app.use('/someOtherResource', someOtherResource')
//Other awesome code
//Return this app.
module.exports = app;
Hope this helps!
Thanks! So, it works well with using a directory of views. I will try the second option while I will do a major refactoring
mph

Resources