setting express js static files and including them in template files - node.js

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"/>

Related

How to include css files for api routers in express?

I am using express and handlebars. The problem is the pages which have urls like http://localhost:5000/api/posts does not include css files. However, routers like http://localhost:5000 or http://localhost:5000/register work completely fine.
directories
app
-server.js
-routes
-api
-posts.js
-public
-css
-images
-views
-layout
-main.handlebars
-posts.handlebars
in server.js . (only important part)
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => res.render('index'));
app.get('/register', (req, res) => res.render('register'));
app.use('/api/posts', require('./routes/api/posts'));
Since I did include app.use(express.static(path.join(__dirname, 'public'))); in server.js, I thought there should not be any problem with the static files.
However, in main.handlebars <link rel="stylesheet" href="css/main.css"> does not work. On the other hand, <link rel="stylesheet" href="../css/main.css"> did work.
Moreover, it also worked if I changed the app.use('/api/posts', require('./routes/api/posts')); to app.use('/posts', require('./routes/api/posts')); Are there any other ways to solve this problem if I don't want to change the routes here?
The error when css is not included was Refused to apply style from 'http://localhost:5000/api/css/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. However, I do not know how to make the public becomes the default path . for static files since I already included app.use(express.static(path.join(__dirname, 'public')));.
For your css file use href="/css/main.css". What you are using is relative path, check network tab in browser debug. It will load http://localhost:5000/api/css/main.css not http://localhost:5000/css/main.css.
Btw if you want to build a RESTful api, I don't think it should response a css file.

Express two static files directory

My folder structure is as the following:
public
css
html
main
pllanet.html
server
server.js
src
img
js
The public folder contains all HTML and CSS codes, and src folder contains img and js files. In server.js, I am using Express to indicated the static files directories as the following:
app.use(express.static(path.join(__dirname, "../public")));
app.use(express.static(path.join(__dirname, "../src")));
When I open pllanet.html, it doesn't seem like the app is picking up the second directory, since the images don't load.
In the pllanet.html file, I have the css route as the following:
<link rel="stylesheet" href="../../css/main/pllanet.css">
<link rel="stylesheet" href="../../css/main/home.css">
Could somebody help me, please? I am really stuck. Also, is it my folder structure a good practice?
Really appreciate your help guys.
You can implemet virtual path
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static
app.use('/static', express.static('public'))
In your code, you could:
app.use('/public', express.static(path.join(__dirname, "../public")));
app.use('/resource', express.static(path.join(__dirname, "../src")));
// and link in html like
<link rel="stylesheet" href="/public/css/main/pllanet.css">
// img or js
<link rel="stylesheet" href="/resource/img/someimage.jpg">

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.

Loading static assets in Nodejs

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')

Express-js can't GET my static files, why?

I've reduced my code to the simplest express-js app I could make:
var express = require("express"),
app = express.createServer();
app.use(express.static(__dirname + '/styles'));
app.listen(3001);
My directory look like this:
static_file.js
/styles
default.css
Yet when I access http://localhost:3001/styles/default.css I get the following error:
Cannot GET / styles /
default.css
I'm using express 2.3.3 and node 0.4.7. What am I doing wrong?
Try http://localhost:3001/default.css.
To have /styles in your request URL, use:
app.use("/styles", express.static(__dirname + '/styles'));
Look at the examples on this page:
//Serve static content for the app from the "public" directory in the application directory.
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
I have the same problem. I have resolved the problem with following code:
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));
Static request example:
http://pruebaexpress.lite.c9.io/js/socket.io.js
I need a more simple solution. Does it exist?
This work for me:
app.use('*/css',express.static('public/css'));
app.use('*/js',express.static('public/js'));
app.use('*/images',express.static('public/images'));
default.css should be available at http://localhost:3001/default.css
The styles in app.use(express.static(__dirname + '/styles')); just tells express to look in the styles directory for a static file to serve. It doesn't (confusingly) then form part of the path it is available on.
In your server.js :
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/public'));
You have declared express and app separately, create a folder named 'public' or as you like, and yet you can access to these folder. In your template src, you have added the relative path from /public (or the name of your folder destiny to static files). Beware of the bars on the routes.
I am using Bootstrap CSS, JS and Fonts in my application. I created a folder called asset in root directory of the app and place all these folder inside it. Then in server file added following line:
app.use("/asset",express.static("asset"));
This line enables me to load the files that are in the asset directory from the /asset path prefix like: http://localhost:3000/asset/css/bootstrap.min.css.
Now in the views I can simply include CSS and JS like below:
<link href="/asset/css/bootstrap.min.css" rel="stylesheet">
What worked for me is:
Instead of writing app.use(express.static(__dirname + 'public/images')); in your app.js
Simply write
app.use(express.static('public/images'));
i.e remove the root directory name in the path. And then you can use the static path effectively in other js files, For example:
<img src="/images/misc/background.jpg">
Hope this helps :)
to serve static files (css,images,js files)just two steps:
pass the directory of css files to built in middleware express.static
var express = require('express');
var app = express();
/*public is folder in my project directory contains three folders
css,image,js
*/
//css =>folder contains css file
//image=>folder contains images
//js =>folder contains javascript files
app.use(express.static( 'public/css'));
to access css files or images just type in url http://localhost:port/filename.css ex:http://localhost:8081/bootstrap.css
note: to link css files to html just type<link href="file_name.css" rel="stylesheet">
if i write this code
var express = require('express');
var app = express();
app.use('/css',express.static( 'public/css'));
to access the static files just type in url:localhost:port/css/filename.css
ex:http://localhost:8081/css/bootstrap.css
note to link css files with html just add the following line
<link href="css/file_name.css" rel="stylesheet">
this one worked for me
app.use(express.static(path.join(__dirname, 'public')));
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/shopping-cart/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/shopping-cart/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/user/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/user/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
Webpack makes things awkward
As a supplement to all the other already existing solutions:
First things first: If you base the paths of your files and directories on the cwd (current working directory), things should work as usual, as the cwd is the folder where you were when you started node (or npm start, yarn run etc).
However...
If you are using webpack, __dirname behavior will be very different, depending on your node.__dirname settings, and your webpack version:
In Webpack v4, the default behavior for __dirname is just /, as documented here.
In this case, you usually want to add this to your config which makes it act like the default in v5, that is __filename and __dirname now behave as-is but for the output file:
module.exports = {
// ...
node: {
// generate actual output file information
// see: https://webpack.js.org/configuration/node/#node__filename
__dirname: false,
__filename: false,
}
};
This has also been discussed here.
In Webpack v5, per the documentation here, the default is already for __filename and __dirname to behave as-is but for the output file, thereby achieving the same result as the config change for v4.
Example
For example, let's say:
you want to add the static public folder
it is located next to your output (usually dist) folder, and you have no sub-folders in dist, it's probably going to look like this
const ServerRoot = path.resolve(__dirname /** dist */, '..');
// ...
app.use(express.static(path.join(ServerRoot, 'public'))
(important: again, this is independent of where your source file is, only looks at where your output files are!)
More advanced Webpack scenarios
Things get more complicated if you have multiple entry points in different output directories, as the __dirname for the same file might be different for output file (that is each file in entry), depending on the location of the output file that this source file was merged into, and what's worse, the same source file might be merged into multiple different output files.
You probably want to avoid this kind of scenario scenario, or, if you cannot avoid it, use Webpack to manage and infuse the correct paths for you, possibly via the DefinePlugin or the EnvironmentPlugin.
The problem with serving __dirname is that __dirname returns the path of the current file, not the project's file.
Also, if you use a dynamic header, each page will look for the static files in a different path and it won't work.
The best, for me, is to substitute __dirname for process.cwd() which ALWAYS donates the path to the project file.
app.use(express.static(process.cwd() + '/public'));
And in your project:
link rel="stylesheet" href="/styles/default.css"
See: What's the difference between process.cwd() vs __dirname?
I was using
app.use(express.static('public'))
When there was no file in the public folder with name index.html.
I was getting the following error in the browser:
"Cannot GET /"
When I renamed the file to 'index.html', it works fine.
Try accessing it with http://localhost:3001/default.css.
app.use(express.static(__dirname + '/styles'));
You are actually giving it the name of folder i.e. styles not your suburl.
I find my css file and add a route to it:
app.get('/css/MyCSS.css', function(req, res){
res.sendFile(__dirname + '/public/css/MyCSS.css');
});
Then it seems to work.
if your setup
myApp
|
|__ public
| |
| |__ stylesheets
| | |
| | |__ style.css
| |
| |___ img
| |
| |__ logo.png
|
|__ app.js
then,
put in app.js
app.use('/static', express.static('public'));
and refer to your style.css: (in some .pug file):
link(rel='stylesheet', href='/static/stylesheets/style.css')
Try './public' instead of __dirname + '/public'.
Similarly, try process.cwd() + '/public'.
Sometimes we lose track of the directories we are working with, its good to avoid assuming that files are located where we are telling express where they are.
Similarly, avoid assuming that in the depths of dependencies the path is being interpreted the same way at every level.
app.use(express.static(__dirname+'/'));
This worked for me, I tried using a public directory but it didn't work.
But in this case, we give access to the whole static files in the directory, hope it helps!
In addition to above, make sure the static file path begins with / (ex... /assets/css)... to serve static files in any directory above the main directory (/main)
Create a folder with 'public' name in Nodejs project
folder.
Put index.html file into of Nodejs project folder.
Put all script and css file into public
folder.
Use app.use( express.static('public'));
and in index.html correct path of scripts to <script type="text/javascript" src="/javasrc/example.js"></script>
And Now all things work fine.
static directory
check the above image(static directory) for dir structure
const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))
// or
app.use("/", express.static(publicDirectoryPath))
app.use((req, res, next) => {
res.sendFile(path.join(publicDirectoryPath,'index.html'))
In your nodejs file
const express = require('express');
const app = express();
app.use('/static', express.static('path_to_static_folder'));
In your pug file
...
script(type="text/javascript", src="static/your_javascript_filename")
...
Note the "static" word. It must be same in nodejs file and pug file.
i just try this code and working
const exp = require('express');
const app = exp();
app.use(exp.static("public"));
and working,
before (not working) :
const express = require('express');
const app = express();
app.use(express.static("public"));
just try

Resources