Files won't load if in root directory? - javascript

I have a weird problem with my file structure. For some reason, after creating the server and running it, I can't get the index.html to run unless it is in a folder. The browser just shows "Cannot GET /". The same can be said for my JS files that are being used in the index.html. Unless they are in folders and not in the root directory itself, they will not load into index.html. Is this normal or is this because of how I have my server.js file set up?
Here's the code:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, './views')));
app.listen(8000, function() {
console.log("Listening on Port 8000");
})
The folder/file structure is:
Root Directory
- node_modules
- views
-js
-script.js
- pages
-about.html
-contact.html
-home.html
- index.html
- server.js
The problem is when the file structure is:
Root Directory
- node_modules
- pages
-about.html
-contact.html
-home.html
- index.html
- script.js
- server.js
The express.static is also pointing to pages instead of views.
Any suggestions on why this is the case? Thanks in advance.

simply, express.static(path.join(__dirname, './views')) will serve all files in folder views
if you go to /pages/index.html . this will check folder view for /page/index.html if exist index.html, it will serve you this file else it will check if you have any handle route logic
You can set multi serve-static.

Related

Express.js server not working all of a sudden - Cannot GET /

My extremely simple express server using node.js suddenly stopped working. It was working fine (only testing it on my local machine for now), then I tried using browserify (which didn't work and I ended up deleting it) and when I went back to the site I was getting a Cannot GET / error.
I've tried uninstalling browserify, re-installing it, uninstalling and re-installing the two npm packages I'm using, even deleting all of my folders and starting from scratch (just pasting in the code on a couple of files). No matter what I still get the same error and I have no idea why. If I open index.html it still opens perfectly, while when I run my server (index.js) it doesn't throw any errors and seems to be listening as it's supposed to.
The server at the moment:
var path = require('path');
var express = require('express');
var app = express();
var dir = path.join(__dirname, 'public');
app.use(express.static(dir));
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
My files are currently structured like this:
public
assets (just has some images)
node_modules
index.html
index.js
package-lock.json
styles.css
Your index.html file should be in public folder and then it will work. At the moment, you have set the static path to public folder which doesn't contain any file.
Since your server's path is /public/index.js, path.join(__dirname, 'public') is resolving to /Users/.../your_directory/public/public. Express cannot find such a directory, so it proceeds down its pipeline. Since you did not define a GET / route, Express throws the error.
I would recommend removing your server file from /public.
Here's what your new directory tree would look like:
my_directory
node_modules
public
assets
index.html
styles.css
server
server.js (index.js in your case)
After you set up your directory tree as such, you can change the following:
var dir = path.join(__dirname, 'public');
// becomes
var dir = path.join(__dirname, '..', 'public');
// The '..' is used to move one directory level up.
Then, you should be able to see index.html when going to http://localhost:3000.

Why CSS and Bootstrap elements disappear with node express server?

I firstly made a basic node server like this:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080, function() {
console.log('Server running on 8080...');
});
Then I replaced it with an express server like this:
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.use(express.static("public"));
app.listen(8080);
console.log("Running at Port 8080");
With the first one, everything worked fine. CSS, JQuery, images etc..., but with the second one, some of my style elements totally disappeared and it can't reach the pictures on the site. What did I miss? How can I solve it?
You are not serving static files.
app.use(express.static("public"))
This would serve all files from /public directly on the root of your server /. If you want to serve them at /static you need to modify the code a bit.
app.use("/static", express.static("public"))
Example
File Structure
├── node_modules
├── package.json
├── public
| └ style.css
|
└── server.js
server.js
var express = require("express")
var app = express()
app.use(express.static("public"))
app.listen(3333)
After running server.js you should be able to access http://localhost:3333/style.css (and every other file in the /public directory)
In order to serve static files have a look at https://expressjs.com/en/starter/static-files.html which shows you can use:
app.use(express.static('public'))
app.use(express.static('files'))
to serve static files from the public and files folder. In your example code you are only serving the index.html.

Sending whole folder content to client with express

I made an html5 game (using GameMaker), which is constituted of an index.html and a folder "html5game" that contains the dependencies of the game - the javascript code and the resources. The problem is the resources are quite numerous and diverse (sounds, sprites, etc.) and The client needs them all to play.
I am looking for a way to send them all without naming them specifically.
I tried the glob module :
var glob = require( 'glob' );
var files = glob.sync( './html5game/**' ).forEach( function( file ) {
require( path.resolve( file ) );
});
but I can't figure a way to send the files using res.sendFile() once I did that.
I tried
var express = require('express');
var app = express();
[...]
app.get('/aeronavale/jeu', function(req, res){
res.sendFile(__dirname + '/aeronavale/index.html');
res.sendFile(files)
});
[...]
app.listen(3000, function(){
console.log('app started on port 3000, yeah !')
})
but it gives me the error :
TypeError: path argument is required to res.sendFile
If you have an other solution, I a also interested. Thanks for your answers !
You will not be able to send multiple file like that with res.sendFile. The most straightforward thing that you can do here would be this:
Put your index.html file and your html5game directory into some common directory, e.g. called html and put it where you have your Node.js program. An example directory layout would be:
/home/you/yourapp:
- app.js (your node program)
- package.json (your package.json etc)
- html (a new directory)
- index.html (your main html to serve)
- html5game (the directory with other files)
- (other files)
Now, in your Node program you can use something like this:
var path = require('path');
var express = require('express');
var app = express();
var htmlPath = path.join(__dirname, 'html');
app.use(express.static(htmlPath));
var server = app.listen(3000, function () {
var host = 'localhost';
var port = server.address().port;
console.log('listening on http://'+host+':'+port+'/');
});
This will serve all of your files (including index.html) on addresses like:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
Of course you still need to make sure that you refer to your assets in your index.html file correctly, for example with:
<script src="/html5game/xxx.js"></script>
in the case of the example layout above.
The top level directory with your static assets (where you have your index.html) is usually called static, public or html but you can call it whatever you like, as long as you use the correct path in your call to express.static().
If you want to have your game available in some path other than the root path then you can specify it to app.use. For example if you change this:
app.use(express.static(htmlPath));
to this:
app.use('/game', express.static(htmlPath));
Then instead of those URLs:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
those URLs will be available instead:
http://localhost:3000/game/ (your index.html)
http://localhost:3000/game/html5game/xxx.js (your assets)
A lot of questions here are related to serving static files with Express so I made a working example and posted it on GitHub so that people could have a working starting point and go from there:
https://github.com/rsp/node-express-static-example
See also some other answers where I talk about it in more detail:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
onload js call not working with node
Loading partials fails on the server JS
Node JS not serving the static image
The workaround for this is to compress the directory using the archiver library and uncompress it on the front end.

Loading scripts in a Node app

This is my folder structure:
- getable_challenge
- node_modules
- stuff
- main.html
- main.js
- backend.js
- README.md
I want to load main.js from within main.html. Previously I had been accessing the page using the URL of file:///Users/adamzerner/code/getable_challenge/main.html, and a simple <script src="main.js"></script> allowed me to load the script.
But then I set up a Node server, at localhost:3000, and now it won't load the script. It's trying to load localhost:3000/main.js, which presumably is the wrong path. I'm not sure how to structure this... what should I do?
Server code (essentially)
var express = require('express');
var app = express();
app.listen(3000);
When you use the "file" protocol like that you aren't even using the web app to serve the script, you are directly accessing it on the local file system. That works fine when you are just running your app on your local machine but it completely breaks when you try to run it as a real app since the browser will have no idea where "file:///..." is, or even have permission to access it.
You need to put the client side scripts into a separate directory, usually named 'public', and then make your application aware of it. If you're using express you would do this:
app.use(express.static(__dirname + '/public'));
You want to put your statically served scripts ("public") into a separate directory so as to control access by your clients. If you just put them into the main directory and made the main directory accessible you could expose all your other files to public view, such as config files that sometimes contain passwords.
It also makes your structure much cleaner.
Try adding this line after var app
app.use(express.static(__dirname));
This should make your resources that are within your servers folder accessible. the var __dirname is the path to where your server is executed.

NODEJS and HEROKU : I can't serve the static files once the server is deployed

ok, I have the simple server which is the following setup:
var port = process.env.PORT || 8080;
var server = http.createServer(app).listen(port);
process.env.PWD = process.cwd();
app.use(express.static(process.env.PWD+'/Public'));
app.get('/',function(req,res) {
res.sendfile(process.env.PWD+ '/index.html');
res.end;
});
I create a git in the folder and I successfully push it to heroku, but when I open it I get this result:
https://leoforio.herokuapp.com/
If you open the console log you will see that it fails to load css and js static files which can't be found,although when I test my app locally this setup works and the files are served as planned.
What am I doing wrong?
P.S. I don't think it a problem with heroku,I believe the problem is within nodejs and uploading the app.
I'm going to guess that the problem lies in how you're specifying the directory for static files.
What I normally see -- and prefer -- is setting up static this way:
app.use(express.static(__dirname + '/public'));
That means Express will look for the static files in the public subdirectory of the same directory that your application file is in. Let's imagine you have two apps, app1.js and app2.js. app1.js is configured the way you have it, using process.cwd() (current working directory), and app2.js is using __dirname as its base. Both of these apps are in /home/drizo/app.
If you do this, both will work correctly:
cd /home/drizo/app
node app1.js # uses cwd + /public = /home/drizo/app/public
node app2.js # uses __dirname + /public = /home/drizo/app/public
However, if you do it like this:
cd /home/drizo # or ANY directory that's not /home/drizo/app
node app/app1.js # uses cwd + /public = /home/drizo/public - WRONG
node app/app2.js # uses __dirname + /public = /home/drizo/app/public
As you can see, app1.js is using the directory that the app was started from. I'm not sure how Heroku starts/restarts apps, but I'm guessing it isn't doing it from the directory you expect.

Categories