How to serve static files to different routes in Express? - node.js

I am creating a site using Express, and when I try to use routes more than one level deep, none of my static files get served. For example, here is my code that is working correctly:
const express = require('express')
const app = express()
const port = 3000
app.use('/public', express.static(__dirname + '/public'))
app.get('/newSite', (req, res) => res.sendFile(__dirname + '/newSite.html') )
app.get('/organizations', (req, res) => res.sendFile(__dirname + '/organizations.html') )
app.listen(port, () => console.log(`listening on port ${port}!`))
I wanted to use something like this for the path:
app.get('/admin/organizations', (req, res) => res.sendFile(__dirname + '/organizations.html') )
I tried messing around with the app.use function because I am thinking that is where my issue is, but I haven't been able to figure it out so far. How do I serve static files to any route?
Edit: Here is the relevant html
<html>
<head>
<link rel="stylesheet" type = "text/css" href = "./public/global.css"/>
<link rel="stylesheet" type = "text/css" href = "./public/organizations.css"/>
</head>
<body>
</body>
<script src = "public/jquery.js"> </script>
<script src = "public/organizations.js"> </script>
</html>

It's got to do with relative path. With express it's safer to use absolute path.
After your route goes one level deep, the html file which is send needs to search one level up to find the static files. (You can confirm: ../public/global.css will actually link static files correctly in your route /admin/organizations)
Simple fix: use absolute path (notice it starts only with /)
<link rel="stylesheet" type = "text/css" href = "/public/global.css"/>

Related

NodeJS: Stylesheet not loading due to unsupported mime type

I'm making an app with NodeJS and Express, and when I start the server I get the following error:
Refused to apply style from 'http://localhost:3000/style.css' because its MIME type
('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Here's my directory tree:
app:
|-node-modules
|-index.js
|-package.json
|-package-lock.json
|-views
|-index.html
|-public
|-stylesheets
|-style.css
Here's my index.js:
const express = require("express");
const app = express();
const path = require("path");
app.use("/static", express.static(__dirname + "/public"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/views/index.html"));
});
app.listen(process.env.port || 3000);
console.log("Server Is Active At Port " + (process.env.port || 3000));
And here's my index.html and style.css:
<!DOCTYPE html>
<html>
<head>
<title>Express App</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="/public/stylesheets/style.css">
</head>
<body>
<h1>Test</h1>
</body>
</html>
body{
text-align: center;
}
Please note that I'm just testing to see if the site works, and this isn't the full code for the site.
You're not showing us the full picture - how are your styles being loaded? Presumably with a <link> tag you opted not to show us. Anyhow, the express.static middleware should take care of setting the correct mime type. You probably aren't providing the correct path to the stylesheet.
Your style tag in your html should look something like this:
<!-- note the "/static" part at the beginning of the url -->
<link rel="stylesheet" href="/static/stylesheets/style.css" />
Try writing
app.use('/public' , express.static(path.join(__dirname, 'public'))); instead of app.use("/static", express.static(__dirname + "/public"));
After that in your html while linking to the css file you can write
<link rel="stylesheet" href="/public/stylesheets/style.css">
Hope this solves the issue
I think this will work. Define path like this:
const staticfiledir = path.join(__dirname,'../public')
Setup for static directories to serve
app.use(express.static(staticfiledir))

Nodejs Express - Why won't my static file be served?

Ive been looking a all kind of posts and just can't understand my mistake. Whatever I do, my css file is just not being served.Does anyone know why?
test/server/app.js:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'browser')));
var PORT = process.env.PORT || 1337;
app.listen(PORT, function() {
console.log('Server is listening!');
});
test/browser/index.html:
<head>
<base href="/" />
<title>Test</title>
<link rel="stylesheet" type="text/css" href="public/style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
<script src="js/app.controller.js"></script>
</head>
<body>
<p>hello world</p>
</body>
</html>
My css file is in test/public/style.css
Your app code can be found in test/server/, which means that path.join(__dirname, 'public') will yield (the absolute path value for) test/server/public, which is not where your CSS file is located.
Instead, you'd want to use this:
path.join(__dirname, '..', 'public')`
Which would make it point to test/public/.
However, this only partly solved the problem, because you're also telling Express that test/public/ is the root directory of the static resources, meaning that your stylesheet's URL is /style.css, not public/style.css.
If you want to keep the public prefix (which you probably do), you need to use this:
app.use('/public', express.static(path.join(__dirname, '..', 'public')));
And in your HTML, be sure to use absolute paths:
<link rel="stylesheet" type="text/css" href="/public/style.css" />

ng-view not working with partials in AngularJS/Express

Everything was working until I tried to display a partial file in ng-view.
/public/app/app.js
angular.module('app', ['ngResource', 'ngRoute']);
angular.module('app').config(function($routeProvider,$locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {templateUrl: '/partials/main', controller: 'mainCtrl'});
});
angular.module('app').controller('mainCtrl', function($scope){
$scope.myVar = "Hello Angular";
});
/server/includes/layout.jade
doctype html 5
html
head
link(rel="stylesheet", href="/css/bootstrap.css")
link(rel="stylesheet", href="/vendor/toastr/toastr.css")
link(rel="stylesheet", href="/css/site.css")
body(ng-app="app")
block main-content
include scripts
/server/includes/scripts.jade (version number are not in the script)
script(type="text/javascript", src="/vendor/jquery/jquery.js") 2.1.0
script(type="text/javascript", src="/vendor/angular/angular.js") 1.2.16
script(type="text/javascript", src="/vendor/angular-resource/angular-resource.js")
script(type="text/javascript", src="/vendor/angular-route/angular-route.js")
script(type="text/javascript", src="/app/app.js")
/views/index.jade
extends ../includes/layout
block main-content
section.content
div(ng-view)
/views/partials/main.jade
h1 This a Partial
h2 {{ myVar }}
and finally server.js
var express = require('express'),
stylus = require('stylus');
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.configure(function (){
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(stylus.middleware(
{
src: __dirname + '/public',
compile: compile
}
));
app.use(express.static (__dirname + '/public'));
});
app.get('/partials/:partialPath', function (req, res){
res.render('partials/' + req.params.partialPath);
})
app.get('*', function(req, res) {
res.render('index');
});
var port = 3030;
app.listen(port);
console.log('Listening on port' + port + '…');
Directory structure:
When I launch the 'node server.js' and go to 'localhost:3030', I get a blank page instead of "This is a Partial Hello Angular" with this HTML:
<!DOCTYPE html 5>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.css"/>
<link rel="stylesheet" href="/vendor/toastr/toastr.css"/>
<link rel="stylesheet" href="/css/site.css"/></head>
<body ng-app="app">
<section class="content">
<div ng-view="ng-view"></div>
</section>
<script type="text/javascript" src="/vendor/jquery/jquery.js"></script>
<script type="text/javascript" src="/vendor/angular/angular.js"></script>
<script type="text/javascript" src="/vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="/vendor/angular-route/angular-route.js"></script>
<script type="text/javascript" src="/app/app.js"></script></body></html>
In the tutorial this config works perfectly, but when I run it, the ng-view is empty. Any idea why?
EDIT:
Node.js runs like a charm. Something must have changed in the conf or I forgot something. In the tutorial everything was installed with bower like I did, and the javascript, hrefs were pointing to /vendor/ in the public directory and it seemed like it worked.
When I looked in the Javascript console, I got this error message for all scripts: SyntaxError: Unexpected token '<' which < is the beginning of an HTTP error message.
So I copied all the called files with error into /vendor/ change the url in "/server/includes/scripts.jade" like "/vendor/jquery/jquery.js" to "vendor/jquery.js" and it worked.
But I feel like I applied a patch. With bower, shouldn't it work with the previous settings?
Not sure how much this will help but I notice all the bower packages are in the 'bower_components' directory. That is the default for bower unless you specify another directory. So, if you want the bower components installed say, '/public/vendor', do the following:
1) create a file called ' .bowerrc ' and save it in your root directory ie. with gitignore, bower.json, etc.
2) in the file put:
{
"directory": "public/vendor"
}
That will load the bower components where you want them. The file ' .bowerrc ' is a config file for bower and you can find the guidance at: http://bower.io/
HTH
Thers is something off in your app.js file. Replace it with this and you should be good to go:
var app = angular.module('app', ['ngResource', 'ngRoute']);
angular.module('app').config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});
});
angular.module('app').controller('mainCtrl', function($scope){
$scope.myVar = "Hello Angular";
});
app.get('*', function(req, res,next) {
if(req.xhr != true)
{
res.render('index');
} else
{
next();
}
});
modify like this

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Can not get CSS file

My directory set up is like this :
app.js
vews
home.html
css
style.css
My home file is like this :
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
</body>
</html>
My app is like this :
var io = require('socket.io'),
url = require('url'),
sys = require('sys'),
express = require('express'),
http=require('http');
var app = express();
var server = http.createServer(app);
var socket = io.listen(server);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.get('/', function(req, res){
res.render('home');
});
app.listen(4000);
sys.puts('server running ' + 'now ' + Date.now());
The problem is when i run the app, css file can not be loaded.
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));
So your final directory structure should look like this
app.js
views
home.html
public
css
style.css
And do not forget to require path module
var path = require('path')
In one of my apps, I have these relevant files in this file structure:
/
index.js
/public
/stylesheets
main.css
/views
/partials
header.ejs
The index.js includes app.use(express.static(path.join(__dirname, '/public')));
Note the /public.
The header.ejs partial includes <link rel='stylesheet' type='text/css' href='/stylesheets/main.css' />
Note the lack of public, it’s implied by the middleware.
In your example, your current directory for static files doesn’t match where you are keeping static files.
Try this:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
This might solve the problem.

Resources