Receiving 404 status when trying to load local files with NodeJS - node.js

I am relatively new to using Node and am trying to make a simple HTML page that can get images, stylesheets, and scripts locally. Every time I try to load a local file, it returns a 404 status. I have tried multiple solutions from StackOverflow and other sources and still cannot get this to work.
Here is my code in app.js:
const app = require('express')();
const http = require('http').createServer(app);
var portNumber = 8085;
app.get('/', function(reg, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, function() {
console.log('Listening on port ' + portNumber);
});
I have a CSS file at public > stylesheets > style.css linked to my HTML document.
<link rel="stylesheet" type="text/css" href="public/stylesheets/style.css" />
I get a 404 error in my browser's console. I also get a MIME error:
The resource from “http://localhost:8085/public/stylesheets/style.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
Any local images I try to load also give a 404 error.
I have tried adding app.use(express.static('public')); to make the public folder the root to serve static content as shown in the Express documentation, but I still got 404 errors.
const express = require('express');
const app = express();
const http = require('http').createServer(app);
var portNumber = 8085;
app.use(express.static('public'));
app.get('/', function(reg, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, function() {
console.log('Listening on port ' + portNumber);
});
I am not sure what I am supposed to do. All I want is to be able to load local files in my HTML document. How do I get these files to be displayed publicly instead of giving a 404 error?

The reason for the mime error is actually confusing - it's due to the browser not being able to find that file.
Remove the /public part of the path location as that is the folder so it's being served from:
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" />
Same for all your other static files: /assets/mypic.png etc
Update your location for the static path as follows:
app.use(express.static(path.join(__dirname, 'public'), {index: false}));
Then, update sendFile to use and absolute path as follows:
return res.sendfile(path.resolve('./index.html'));
// or
return res.sendfile(path.join(__dirname, 'index.html'));

You should try using
app.use(express.static(__dirname + "/public"));
That way express knows where to search for that public folder.

Related

AWS Elastic Beanstalk wont load static files from public folder for nodejs app

I have deployed the nodejs application with aws eb deploy, client.js is not getting loaded in index.hbs files and returning 404 error (Failed to load resource: the server responded with a status of 404 (Not Found))
I have tried all the step in the internet and wasted two days for this.
Can any one please help me here ? I am doing anything wrong here?
I have tried the solution in this stackover flow page Elastic Beanstalk Static Folder 403 Error but no luck
staticfiles.config(NodejsPlayGround.elasticbeanstalk\staticfiles.config) file
option_settings:
aws:elasticbeanstalk:container:nodejs:staticfiles:
/public: public
index.hbs(NodejsPlayGround\views\index.hbs) file
<!DOCTYPE html>
<html>
<head>
<title>NodeSeverTest</title>
<script src="js/client.js"></script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
server.js(NodejsPlayGround\server.js) file
'use strict';
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
const views_path = path.join(__dirname, 'views');
const static_path = path.join(__dirname, 'public')
app.set('view engine', 'hbs');
app.set('views', views_path);
app.get('', (req, res) => {
res.render('index', {
title: 'Weather App',
name: 'ArunKumar Arjunan'
}
);
});
app.listen(port, () => {
console.log('server started on port ' + port);
});
client.js(NodejsPlayGround\public\js\client.js) file:
console.log('client side java script file is loaded');
client.js file needs to be loaded in index.hbs file
I find that contrary to the AWS documentation on this, the folder path also needs a leading slash — i.e. you map /public to /public (not just public), or /static to /static (not just static).
I figured this out by inspecting the nginx error log and conf files on my EB instances, and both showed that it was looking for my static files in /var/app/currentstatic instead of /var/app/current/static.

Multiple routes for static html pages in Express

I am trying to serve 2 static HTML pages from Express but whilst the index.html is correctly served I get an error when I try to access the /about route:
Error: ENOENT: no such file or directory, stat
'/var/www/html/myapp/about.html'
at Error (native)
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/html_files'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/about', function(req, res) {
res.sendfile(__dirname + '/about.html');
});
app.listen(3000);
I can update the '/about.html' to '/html_files/about.html' and then it works but whilst this solves the issue I can't understand why it wouldn't work as it is.
Looks correct.
app.get('/'... will be ignored, as server already has found static index.html matching this request.
app.get('/about'... fails because of incorrect url to file you're trying to send. If you ask for /about.html it'll be sent by static middleware correctly.

Cant load css file

I'm trying to use the login templates (Took from: 50 Free HTML5 And CSS3 Login Forms For Your Website 201
My directory set up is like this :
-css
|
-- style.css
- js
|
-- index.js
|
index.html
The head of the index.html file looks:
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
and the body contains the includes scrips:
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
My node.js looks:
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// css
var path = require('path')
app.use(express.static(path.join(__dirname, 'public')));
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
/*
app.get('css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('css/style.css', {root: __dirname })
})
*/
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
When loading the html file I'm getting the error:
GET http://127.0.0.1:3001/css/style.css
I have tried to look for solution at:
Can not get CSS file
And created the public folder and copy the css folder inside, but it still doesnt work.
How can I load the css & js files ?
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
app.get('/css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('LoginTemplate/css/style.css', {root: __dirname })
})
app.get('/js/index.js', function (req, res) {
console.log('Get: js/index.js');
res.sendFile('LoginTemplate/js/index.js', {root: __dirname })
})
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
Everything looks good in your code and folder setup. From the URL you are posting (http://127.0.0.1:3001/css/style.css), I am guessing that the error lies in your server instance. Check the definition files and make sure that the server has permission to read css/style.css.
I have run into this problem when the file and folder do not have the right permissions. A quick check for this is running something similar to sudo chmod -R 0777 [path_to_your_project] (linux and Mac systems will use this command). This command gives full access to all users and guests to read, write and execute your files and is a quick way to verify whether the problem is user rights.
I have also run into this same problem when my web server is not correctly configured. In those cases, I had accidentally allowed the web server to share all files in the root folder (eg: /var/www ), but not any sub folders, so (using the example) the folder /var/www/images would be parsed by the web server and seen as an area that is protected. In this case, the Web Server has access, but it refuses to serve the files based on the configuration rules.
I hope one of these two fixes helps direct you down the right path to a solution.
Good luck!

NodeJS+Express:As I use links to navigate I cannot load the CSSs

I am very novice at Node.
I made the server run as follows (index.js):
var express = require('express'),
views = require('./routes/views');
var app = express();
// Get an instance of router
//var router = express.Router();
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
app.use('/', views);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
I use the router in this way, setting also the, I guess correct ones, paths to the static content (views.js):
var express = require('express');
var path = require("path");
var router = express.Router();
router.use('/assets', express.static(__dirname+'/keenIO/assets'));
router.use('/specificAssets', express.static(__dirname+'/keenIO/examples'));
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
router.get('/', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/index.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/rules', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/rules.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/json', function(req, res) {
//res.send('POST handler for /views route.');
var fs = require('fs');
//res.send('HOLA MUNDO');
var obj;
fs.readFile('network-big.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
res.send(obj);
});
});
module.exports = router;
So, In the .html file I use for example this to reach to the css, and similar to reach to the javascript files:
<link rel="stylesheet" type="text/css" href="assets/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="assets/css/keen-dashboards.css" />
<link rel="stylesheet" type="text/css" href="specificAssets/connected-devices/connected-devices.css" />
I start this and everything is fine, but as I try to load the same index.html for example clicking on a link ( with the path to it: specificAssets/connected-devices/index.html) it has no style at all.
EDITED 25/10/16 3:30 p.m:
Well, inspecting the element with Chrome, as I click on the links I get doubled one part of the patch, getting for some static resources http://localhost:3000/assets/assets/resource.{css/js}
But it appropriately loaded the first time I access to the .html with http://localhost:3000. I am confused...
Any advise will be very appreciated.
Best regards,
Iván
Create a proper structure and keep all your html files in a views folder and do it following way that will work for you And for styling just keep your css in html file only or keep them in same folder and require file in html Easiest way to do is to keep your html and style in same file
router.set('views', path.join(__dirname, 'views'));
router.get('/', function(req, res) {
res.render('index');
});
If you want to use a proper structure then you need to know this thing as well
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')));

Cannot GET / Express ERROR

I am learning Mean.js stack, and try to build an app. I have installed Express, and it works. When I tried to configure my static file ( html, js, images, etc.), then things broke.
Here are my files:
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + "public"));
app.listen(3000);
console.log('Server running on port 3000');
My html file is very simple :
<!DOCTYPE>
<html>
<head>
<title>Contact List App</title>
</head>
<body>
<h1>Contact List App</h1>
</body>
</html>
So when I start the server : node server.js, and then I type http://localhost:3000/ in the browser, I get the "Cannot Get" error.
Where is the problem?
__dirname doesn't have a trailing slash, so you need to provide one yourself when building the static root:
app.use(express.static(__dirname + "/public"));
^ this needs to be there
You need to make sure the route exists. Also, it is a better practice to use path for joining strings. Also, make sure the directory public exists and the file index.html is inside that folder.
var path = require('path');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index.html');
});
app.listen(3000);
console.log('Server running on port 3000');

Resources