can express.static find your mounting file - node.js

I have seen some code online and was wondering how the index.HTML was getting rendered when we are not using any app.get()
the public file structure follow like this:
css(folder),
js(folder),
chat.html,
index.html,
const path = require('path');
const express = require('express');
const app = express();
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

When an incoming request matches a directory name that express.static() is configured for, then express.static() will look for an index.html file in that directory and, if found, will serve it.
You can see this feature mentioned here in the doc, in the index option you can pass express.static() that allows you to specify the name of the index.html file to look for (default value is index.html) or you can set it to false to disable the feature.
So, in your code example, with this:
app.use(express.static(path.join(__dirname, 'public')));
an incoming http request for / will look for public/index.html and, if found, will serve it automatically. Similarly a request for /foo will look first for /public/foo and if that is present and is a directory, then it will look for public/foo/index.html and, if found, will serve it.

Related

Node Express - requesting any file returns 404 not found

I have deployed an AWS LightSail Node server with Express on it.
Starting the app on port 3000 correctly activates app.js and display in the browser the projected string (http://my.ip.address:3000):
Welcome to the Whiteboard server! this is the home page on port 3000 with base dir: /opt/bitnami/apache/htdocs/whiteboard
This is the app.js:
const express = require("express");
const app = express();
const port = 3000;
global.__basedir = __dirname;
app.use(express.json());
app.listen(port, () => {
console.log(`Whiteboard listening on port: ${port}`);
});
app.get("/", (req, res) => {
res.send(`Welcome to the Whiteboard server! this is the home page on port ${port} with base dir: ${__basedir}`);
});
However, Trying to request any file residing in the root folder (...apache/htdocs/whiteboard) such as:
http://my.ip.address:3000/Jeanette_Blog1.png
http://my.ip.address:3000/index.html
Always returns this message in the browser:
Cannot GET /Jeanette_Blog1.png
Shows as 404 error in the console.
Btw, although the path shows apache, I have actually installed node with needed modules and express - as can be seen in the app.js file up here. The apache is just part of the node image AWS LightSail creates through their partner Bitnami.
What am I missing?
An express server by itself does not serve any files by default. If you want to serve a directory or a directory hierarchy of static files, you have to use express.static() (or something similar) in a route definition.
You should not configure express.static() to point at the same directory that contains your server code because that would enable people to look at your server files. It is a popular convention to make a sub-directory (often called "/public", either below or at the same level as your server files. Here's an example with express.static() configured for a directory at the same level. You would add this line:
app.use(express.static(path.join(__dirname, "../public")));
And, it would all look like this:
const express = require("express");
const app = express();
const path = require('path');
const port = 3000;
global.__basedir = __dirname;
// serve public files
app.use(express.static(path.join(__dirname, "../public")), {index: false});
app.use(express.json());
app.listen(port, () => {
console.log(`Whiteboard listening on port: ${port}`);
});
app.get("/", (req, res) => {
res.send(`Welcome to the Whiteboard server! this is the home page on port ${port} with base dir: ${__basedir}`);
});
Then, you would move your static files such as index.html and Jeanette_Blog1.png to that /public directory. They can be referred to from the browser as URLS such as /index.html and /Jeanette_Blog1.png. The express.static() middleware will check the incoming path to see if it matches a filename in the /public directory and, if so, it will serve it. If it doesn't match a file, then it will continue routing to other route handlers you have defined.

I am new to node js and I am not able to create my server please help me... please explain my errors [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Please help me in creating this express server
const express = require('express');
const path = require('path');
const log = console.log;
const app = express();
const port = process.env.PORT || 8000;
app.use(express.static('static'))
app.get('/', express.static(path.join(__dirname, 'index.html')))
app.use('/about', express.static(path.join(__dirname, 'about.html')))
app.use('/contact', express.static(path.join(__dirname, 'contact.html')))
app.listen(port);
console.log('Server started at http://localhost:' + port);
To start with express.static() is not being used correctly. You pass express.static() a directory name, not a filename. It then takes the path from the URL and looks for that path in the directory you passed to it. If it doesn't find a direct match, it also tries a set of default file extensions such as .html. So, all your express.static() lines are wrong.
And, to fix that, you need to move your about.html and other static HTML files outside of the same directory as your code. Those public HTML files need to be in their own directory.
So, let's say that you move them to a sub-directory named public below __dirname.
That would lead to this:
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 8000;
// this will serve any matching file it finds in the 'public' sub-directory
// It will match / to index.html
// It will also match /about to about.html
// and /contact to contact.html
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log('Server started at http://localhost:' + port);
});
Note, you do NOT want to point express.static() at your __dirname directory because then that would allow an attacker to get access to your server code and/or security credentials. But, if you move the public files to a sub-directory and point express.static() only at that sub-directory, then there is no risk of serving anything except the files you explicitly put in the public sub-directory which can be completely safe.

How does express know this routing?

I create a simple express server and serve the static files
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Listening on port 3000')
})
When I head to localhost:3000, the index.html in my public directory renders for the route ' / '. I didn't explicitly write the route in my index.js file. How does express know this?
I've tried changing the file name from index.html to random.html and I get an error. CANNOT GET /
As mentioned in the comments, app.use(express.static('public')) is responsible for this. This will essentially serve all files in the public folder you have in the project. If you have an index.html in the public folder, then that will be served at the / endpoint automatically. This is a convention that most websites follow, and is documented in this SO post.
Here is the relevant documentation on express.static(...): https://expressjs.com/en/starter/static-files.html

Serving css and javascript files

I am beginner with node. I am trying to serve a file. The hierarchy of my project looks like
app
modules
node_modules
public
css
index.css
html
index.html
javascript
routes
main.js
inside main.js
var express = require('express');
var app = express();
var path = require('path')
var port = 8080;
app.use("/styles", express.static(path.join(__dirname + '../public/css')));
app.use("/scripts", express.static(__dirname + '../public/javascript'));
app.get('/' , function( req , res ){
res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)
i want to serve a file on / route. It works fine , but css and javascripts are not loaded - it throws error in browswer console
http://localhost:8080/css/index.css Failed to load resource: the
server responded with a status of 404 (Not Found)
What is the right way to set path to css? I have trouble to find the righ solution.
Thanks!
The problem is with your path definition. When you use path.join you should pass strings to it and this method will join them with platform specific separator as a delimiter, then normalizes the resulting path.
so your styles path should be:
app.use("/styles", express.static(path.join(__dirname, 'public', 'css')));
and your styles will serve from:
http://localhost:8080/styles/index.css
Because you are using a virtual path prefix (here: /styles).
If you dont mind platform specific separator, i. e. know that your server will be a unix like environment and dont need a virtual path prefix then just use:
app.use(express.static(__dirname + '/public'));
and your styles will serve from css dir:
http://localhost:8080/css/index.css
Because you set another routes. Change your routes to static files. Use this:
app.use(express.static('../public'));

Can't serve up a static directory using Node 0.9 and latest express 4.11.2

Using the following simple Node server
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(3000);
console.log('Listening on port 3000');
I have of course put a 'public' directory in my root and also dropped a index.html file in it but when i point my browser to
http://localhost:3000/public/
I get
Cannot GET /public/
The problem is how you're mounting express.static middleware. In your example you're mounting it to the root of your application.
So, in your example you should be able to access content of /public directory from http://localhost:3000/.
So, all you need is to specify a mounting point for express.static middleware:
app.use('public', express.static(path.join(__dirname, 'public')));
You should also keep in mind that express.static don't have a default index page. So, if you have no index.html in your public directory you'll get 404 anyway (express.static won't list your files like apache do).
This one caught me out as well when starting with express.
http://localhost:3000/public/ won't be accessible.
For example lets say you have a css folder inside of the public directory with a file called styles.css
Your browser would be able to access that file at http://localhost:3000/css/styles.css.
The express documentation on express.static can be found here: app.use (under the two example tables)
edit 1: See this answer here.
edit 2: #Leonid Beschastny answer is correct, I didn't see that a path to a folder was missing in app.use(express.static(path.join(__dirname, 'public')));

Resources