Loading static assets in Nodejs - node.js

What is the correct approach to loading static files. I'm trying to use Semantic UI. I have followed the basic steps here: http://semantic-ui.com/introduction/getting-started.html. I have Node installed, NPM installed, ran the gulp process and built the files. I have also required the files like this:
link(rel='stylesheet', type='text/css', href='/semantic/dist/semantic.min.css')
script(src='semantic/dist/semantic.min.js')
My project structure is this:
server.js
views/
index.jade
semantic/
dist/
semantic.min.css
semantic.min.js
I have checked in the browser and there is no console error but those files aren't listed as a resource. I have checked the server logs and there's no error.
The only thing I can think of, is that I need to set up a public directory to serve static files like:
app.use(express.static(path.join(__dirname, 'public')));
Edit
I have attempted to do this:
app.use(express.static('public'));
And have moved the files into the public directory. It loads because I can navigate to them in the browser but they aren't being applied.
Is there anyway to require them from the semantic folder? I like them to be built and required from the same space.
Edit
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title
<script src="js/jquery.min.js"></script>
<link rel="stylesheet" href="css/semantic.min.css">
<script src="js/semantic.min.js"></script>
</title>
<body>
<button class="ui button"> Follow</button>
</body>
</head>
</html>
Serverjs:
var express = require('express'),
ejs = require('ejs'),
path = require('path'),
app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', function(req, res) {
res.render('index');
});
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Node is listening at http://' + host + ':' + port);
});

Add this line in your app.js file.
app.use(express.static(path.join(__dirname,'public')));
Then create a folder named public in the project root directory and move the css and js files to this folder. A better way of organising things would be to
create folders named css and javascript inside the public directory and then place css and js files in these folders.
Then in your template file, include these by adding :
link(rel='stylesheet', type='text/css', href='css/semantic.min.css')
script(src='javascript/semantic.min.js')

Related

setting express js static files and including them in template files

I have set my static folder to public (in the root of my app folder) within the app.js.
But still the handlebars layout files when linking the css files, could not find the files within the public folder.
// app.js code:
// init app
var app = express();
// view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','handlebars');
app.engine('handlebars',expressHandlebars({defaultLayout:'layout'}));
// middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());
// set static folder
app.set(express.static(path.join(__dirname,'public')));
handlebars layout file:
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
First of all you must use absolute path as mentioned by robertklep in comments.
Now the problem, you are using app.set thats the problem, you have to use .use method not .set.
Now about how you should structure your directory, I recommend assigning a directory path like '/public' for accessing public files. It can be done like this :
//app.use not .set
app.use('/public', express.static(path.join(__dirname,'public')));
//see the first argument in above line it assigns which directory path is used to access the public file through URL
After this is done you can access the files you need like this :
<link rel="stylesheet" type="text/css" href="/public/css/bootstrap.min.css"/>

Node express server not serving images folder

When I run my bundled React app on the production server, it can't find my image files and I'm not sure why. I'm fairly sure it's got something to do with my node express configuration and/or my .ejs template file.
server.js
var express = require('express')
var app = express();
const path = require('path');
app.use('/static', express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('*', function (req, res) {
res.render("index");
});
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
app.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Production Server</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=BenchNine" rel="stylesheet">
<link rel="stylesheet" href="../static/css/main.css">
</head>
<body>
<div id="root"></div>
<script src="../static/js/bundle.js"></script>
</body>
</html>
My CSS stylesheet is called in the template file, and all JS is bundled into bundle.js which is referenced in the script tag. I'm not sure how to get my application to recognise the /img folder though, as at the moment it doesn't.
Here's my file structure:
- static
- css
- main.css
- js
- bundle.js
- img (contains all image files)
When I run the app however, and I open 'Sources' in Chrome console, the /img file is not being served.
I thought this line indicates that express serves everything in the /static folder...
app.use('/static', express.static(__dirname + '/static'));
...yet only two out of three files are being served.
Would massively appreciate if anyone can tell me where I'm going wrong with my setup.
Thanks in advance.
The source tab in the DevTools will only show the contents that are being used by the browser in your case index.ejs, it's only using .js and .css files
in Index.ejs you are loading
<script src="../static/js/bundle.js"></script> and <link rel="stylesheet" href="../static/css/main.css">
so that means the middleware app.use('/static', express.static(__dirname + '/static')); will check whether or not the /js/bundle.js and /css/main.css are there in the static folder, if yes it will serve them, if not then will give file or folder not found.
That means whatever you will load from the static folder in index.ejs or use in index.ejs only that contents and files will be present in the source tab.
Try adding a image in index.ejs from static folder and then view the source tab
or remove <script src="../static/js/bundle.js"></script> and view source tab you won't see JS folder as it's not been used by index.ejs
Always reload the server

unabe to get static css files at express.js

i am trying by first express web app and I am using ejs template to render my web page and css to style my pages.
but server is unable to render css file from public folder. i put the static file path at express .js as follow
express = require('express'),
var app = express();
i tried to put static file path to express.js
// app.use(express.static('../public'));
app.use("/public",express.static(__dirname + '/public'));
// app.use(express.static('../../public')); //./
// app.use('/', express.static(__dirname + '/public'));
//app.use(express.static(__dirname + '../../public'));
and gave link to to my signup.ejs page
<link href="/public/mystyle.css" rel="stylesheet" type="text/css">
my directory structure as follow
app
|-view
|- signup.ejs
public
|-mystyle.css
express.js
When i started my server its give me 404 not found error. although my localhost is working good only problem is my web page is unable to get css file in webpage
Are you sure the port you have entered in the app.listen() is correct?
try
app.listen(port no., 'your localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
Change the following two things:
Make link relative: app.use("/public",express.static(__dirname + './public'));
No need of navigating to /public again, since express.js already searches for static files in this folder: <link href="/mystyle.css" rel="stylesheet" type="text/css">
See: http://expressjs.com/en/starter/static-files.html

Find a css file node js

Hi I'm new to nodejs and I've just succeed to deploy a nodejs app online. Now I would like to know how to link CSS, JS or image files be cause when I try to do it like I used to, I get the error GET (not found).
The folder architecture is:
--public
--assets
--css
index.css
--js
--views
--index.ejs
--node modules
app.js
package.json
Assuming that I want to code the link index.css in index.ejs, what I need to write in my app.js file please.
app.js code:
var express = require('express');
var app = express.createServer();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.render('index');
});
app.listen(8080,'IP_ADRESS');
index.ejs code:
<link rel="stylesheet" type="text/css" href="/css/index.css">
The basic set up of serving static files in express :
var express = require("express");
var app = express();
...
app.use(express.static(__dirname + '/public'));
...
app.listen(3000);
Now in your .ejs in order to load the css styles or js scripts :
<link rel="stylesheet" href="/css/index.css"/>
First, there's a thing called a static file. Basically, that's a file that's sent over the internet without any kind of modification. Image and CSS files are typically static files.
It looks like you've put your static files in a folder called public.
Express has a built-in feature for sending static files, called express.static. You can use it like this:
// Require the modules we need.
var express = require('express');
var path = require('path');
// Create an Express app.
var app = express();
// Get the path to the `public` folder.
// __dirname is the folder that `app.js` is in.
var publicPath = path.resolve(__dirname, 'public');
// Serve this path with the Express static file middleware.
app.use(express.static(publicPath));
// ...
You should now be able to see static files. If your site is normally accessible at http://localhost:3000, you'll be able to see index.css at http://localhost:3000/css/index.css.
If you want to know way too much about express.static, you can check out a blog post I wrote that goes into Express's static files in depth.

Not able to loading static files with express

Tried all possible combinations I can think of but not able to load static files using express server.
Dir Structure
app
--todoApp.html
----server.js //node file
----jquery.js
----backbone.js
Node server
var http = require('http'),
express = require('express');
var app = express();
app.listen(3000);
app.set('views', __dirname);
app.use(express.static(__dirname));
app.engine('html', require('ejs').renderFile);
console.log(__dirname);
app.get('/', function(req, res){
//res.send('Whats up?');
res.render('../todoApp.html');
});
__dirname prints as app/js ehich is correct. But page loads with error the server responded with a status of 404 (Not Found) http://localhost:3000/js/jquery.js.
HTML loads the script like this:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/underscore-min.js"></script>
<script type="text/javascript" src="js/backbone.js"></script>
I tried multiple things but it does not work.
Tried following:
app.use('/js',express.static(__dirname));
or
app.use('/',express.static(__dirname));
Please help.
Since the current directory is already the js directory, you don't need to specify it in the <script> tags when loading your JavaScript files:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone.js"></script>
When you set a static directory in express, that directory effectively becomes the root, so all of your static file paths should be relative to that directory.
Also, it is probably not a good idea to have your server-side code in a static directory, since this would allow anyone using your server access to your server side code. It would be better to put all of your static files in a different directory, and set that as the static directory in express.

Resources