Why is Express not serving up my static files? - node.js

URL: http://example.com:8080/js/file.js
var express = require('express');
app = express();
app.use(express.static('public'));
app.listen(8080);
Directory Structure
/
index.js (loaded node file)
public (folder)
----js (folder)
----file.js (requested file)
Error: Cannot GET /js/file.js

Provide the full path to the directory:
app.use(express.static(__dirname + '/public'));

It might be easier to set up something like what is described in this tutorial
http://www.mfranc.com/node-js/node-js-simple-web-server-with-express/
/* serves all the static files */
app.get(/^(.+)$/, function(req, res){
console.log('static file request : ' + req.params);
res.sendfile( __dirname + req.params[0]);
});

What version of express are you using? For me, using 3.4.0, the following didn't work:
app.use(express.static(__dirname + '/public'));
but this did:
app.use("/public", express.static(__dirname + '/public'));
Not sure if its version specific, but usign the first syntax if was failing with the same Error: Cannot get XXX error

Related

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.

NodeJS and Express: Add auth middleware to static path

I have a node app running express as the web app framework and I use Stormpath for authentication.
Storm path gives the ability to protect a route with several middlewares,
for example:
router.get('/user_data_api', stormpath.apiAuthenticationRequired, function(req, res) {
res.send('hello you are authenticated!");
});
});
What I want to do is to add authenticationRequired as a middleware to the static definition of express:
app.use(express.static(__dirname + '/public'));
This could be achieved by adding a route to the static assets, so if I have a file ./public/index.html I can set the route like this:
app.use('/secured-assets',
stormpath.auth_fn, express.static(__dirname + '/public'));
But then the file will be in
www.mydomain.com/secured-assets/index.html
And I want it in
www.mydomain.com/index.html
Help?
Do just:
app.use(stormpath.auth_fn, express.static(__dirname + '/public'));
It'll add stormpath.auth_fn and express.static(__dirname + '/public') middlewares to the / path and, hence, will protect every route.
This worked for me with Express ^4.13.4 and Stormpath ^3.1.2
app.use(stormpath.loginRequired, express.static(__dirname + '/public'));

Express 3 - Serving static scripts/styles - Error: Failes to load resource (404)

I am new to node and server-side development in general and started having a look at it today so mind my question. I have looked for suiting answers in previous post, yet somehow every suggested solution was criticized by many users.
I can't serve static scripts/styles due to the following error:
Failed to load resource: the server responded with a status of 404 (Not Found)
I am using express 3.1.0.
Here is my code:
app.js
var express = require('express');
var app = express();
var routes = require('./routes');
app.configure(function () {
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
});
app.get('/', routes.home);
app.get('/about', routes.about);
app.get('/blog', routes.blog);
app.get('/faq', routes.faq);
app.get('/terms', routes.terms);
app.get('/privacy', routes.privacy);
app.get('/jobs', routes.jobs);
app.get('/press', routes.press);
app.listen(8080);
index.js (routes)
exports.home = function(req, res){
res.render('home', { title: "Home"});
};
exports.about = function(req, res){
res.render('about', { title: "About" });
};
etc...
layout.jade
doctype 5
html
head
title= title
link(rel='stylesheet', href='public/styles/bootstrap.css')
body
block content
br
a(href='../') Home
br
a(href='../about') About
br
etc...
home.jade
extends layout
block content
p Home
When you setup server middlewere it looks for requests at the root unless specified otherwise if you are looking for a stylesheet in "public/styles" you request it at just "/styles"
to make the middlewere answer to requests to /public change it to
app.use('/public', express.static(__dirname + '/public'));
I tried using
app.use('/public', express.static(__dirname + '/public'));
instead of
app.use(express.static(__dirname + '/public'));
and it worked.
However according to the first answer in this post: express.js not serving my image it is not considered good. I can't understand why? And what else would be a better solution?

Error: Failed to lookup view in Express

Note: my auto answer at end of the post
I'm trying to make a better experience of nodeJS and i don't really like to get all the script in one file.
so, following a post here i use this structure
./
config/
enviroment.js
routes.js
public/
css/
styles.css
images
views
index
index.jade
section
index.jade
layout.jade
app.js
My files are right now:
app.js
var express = require('express');
var app = module.exports = express.createServer();
require('./config/enviroment.js')(app, express);
require('./config/routes.js')(app);
app.listen(3000);
enviroment.js
module.exports = function(app, express) {
app.configure(function() {
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade'); //extension of views
});
//development configuration
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
//production configuration
app.configure('production', function() {
app.use(express.errorHandler());
});
};
routes.js
module.exports = function(app) {
app.get(['/','/index', '/inicio'], function(req, res) {
res.render('index/index');
});
app.get('/test', function(req, res) {
//res.render('index/index');
});
};
layout.jade
!!! 5
html
head
link(rel='stylesheet', href='/css/style.css')
title Express + Jade
body
#main
h1 Content goes here
#container!= body
index/index.jade
h1 algoa
The error i get is:
Error: Failed to lookup view "index/index"
at Function.render (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\application.js:495:17)
at render (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\response.js:614:9)
at ServerResponse.render (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\response.js:638:5)
at c:\xampp\htdocs\nodejs\buses\config\routes.js:4:7
at callbacks (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:177:11)
at param (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:151:11)
at pass (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:158:5)
at Router._dispatch (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:185:4)
at Object.router [as handle] (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:45:10)
at next (c:\xampp\htdocs\nodejs\buses\node_modules\express\node_modules\connect\lib\proto.js:191:15)
But i don't really know what is the problem...
I'm starting thinking is because the modules exports...
Answer:
Far away the unique solution i found is to change the place i defined app.set('views') and views engine
I moved it to the app.js and now is working well.
var express = require('express');
var app = module.exports = express.createServer();
require('./config/enviroment.js')(app, express);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
require('./config/routes.js')(app);
app.listen(3000);
I don't really understand the logic behind this but i gonna supose it have one.
Adding to #mihai's answer:
If you are in Windows, then just concatenating __dirname' + '../public' will result in wrong directory name (For example: c:\dev\app\module../public).
Instead use path, which will work irrespective of the OS:
var path = require ('path');
app.use(express.static(path.join(__dirname + '../public')));
path.join will normalize the path separator character and will return correct path value.
npm install express#2.5.9 installs the previous version, if it helps.
I know in 3.x the view layout mechanic was removed, but this might not be your problem. Also replace express.createServer() with express()
Update:
It's your __dirname from environment.js
It should be:
app.use(express.static(__dirname + '../public'));
It is solved by adding the following code in app.js file
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
I had the same error at first and i was really annoyed.
you just need to have ./ before the path to the template
res.render('./index/index');
Hope it works, worked for me.
You could set the path to a constant like this and set it using express.
const viewsPath = path.join(__dirname, '../views')
app.set('view engine','hbs')
app.set('views', viewsPath)
app.get('/', function(req, res){
res.render("index");
});
This worked for me
Check if you have used a proper view engine.
In my case I updated the npm and end up in changing the engine to 'hjs'(I was trying to uninstall jade to use pug).
So changing it to jade from hjs in app.js file worked for me.
app.set('view engine','jade');
In my case, I solved it with the following:
app.set('views', `${__dirname}/views`);
app.use(express.static(`${__dirname}/public`));
I needed to start node app.min.js from /dist folder.
My folder structure was:
This problem is basically seen because of case sensitive file name.
for example if you save file as index.jadge than its mane on route it should be "index" not "Index" in windows this is okay but in linux like server this will create issue.
1) if file name is index.jadge
app.get('/', function(req, res){
res.render("index");
});
2) if file name is Index.jadge
app.get('/', function(req, res){
res.render("Index");
});
use this code to solve the issue
app.get('/', function(req, res){
res.render("index");
});
Just noticed that I had named my file ' index.html' instead for 'index.html' with a leading space. That was why it could not find it.
This error really just has to do with the file Path,thats all you have to check,for me my parent folder was "Layouts" but my actual file was layout.html,my path had layouts on both,once i corrected that error was gone.
i had the same problem but, i change the name of the file from index.html to index.ejs and works!!!!
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index');
});
router.get('/contact', (req, res) => {
res.render('contact', { title: 'Contact Page' });
});
module.exports = router;
and index.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
//settings
app.set('port', 4000);
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'ejs');
//middlewares
//routes
app.use(require('./routes'));
//static files
//listening
app.listen(app.get('port'), () => {
console.log('Server is running at http://localhost:'+app.get('port')+'/');
});
update:
add this in index:
app.engine('html', require('ejs').renderFile);
I change the views folder name to views_render and also facing the same issue as above, so restart server.js and it works for me.
I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.
I changed the filename from index.js to index.pug
Then used in the '/' route: res.render('index.pug') - instead of res.render('index')
Set environment variable: DEBUG=express:view
Now it works like a charm.
I had this issue as well on Linux
I had the following
res.render('./views/index')
I changed it too
res.render('../views/index')
Everything is now working.
I had the same issue. Then just check the file directory in your explorer. Sometimes views folder isn't present.
In my case, I was deploying my web app on a Windows Server and I had a service set up to run a .bat file with only one line as content:
node D:\webapp\app.js
But this was not enough. I also had to change the directory before that, so I added the following line at the beginning of the .bat file:
cd D:\webapp
app.get("/", (req, res) => {
res.render("home");
});
// the code below brought the error
app.get("/", (req, res) => {
res.render("/");
})
I was facing this error because i mistakenly deleted my error.ejs file and it was being called in app.js file and was not found in views as it was already deleted by me

express.js not serving my image

I don't understand whats going wrong here.
directory structure:
app/server.js
app/public/index.html
app/public/js/main.js
app/public/img/car.png
server.js
var fs = require('fs') ,express = require('express'),
app = express.createServer();
app.use(express.static(__dirname + "/public"));
app.get('/', function(req, res){
fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, text){
res.send(text);
});
});
app.listen(8080, function(){
console.log('Server listening on %d', app.address().port);
});
main.js
var marker = new google.maps.Marker({
map:map,
position:coords,
icon: 'img/car.png'
});
erroroutput:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/img/car.png
All my css files and js files load with no problem.
What am I doing wrong?
UPDATE
This was due to the file being named car.png.png
When browsing in windows, fileextensions were not visible so I was fooled into thinking the name was really car.png
Lesson learned!
Change this line
app.use(express.static(__dirname + "/public"));
To this
app.use('/public', express.static(__dirname + "/public"));
Try using an absolute path - /img/car.png

Resources