How does express know this routing? - node.js

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

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.

can express.static find your mounting file

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.

Why I'm getting a blank page from running a node server that point to the /dist folder of an Angular app?

My simple node server is:
const express = require('express');
const app = express();
app.get('*', (req, res) => {
res.sendFile(__dirname + '/dist/page/index.html');
})
app.listen(3335, () => { console.log('Server is listening on 3335'); });
But I'm getting the index file that seems not running the main.js
The Angular app, at the moment it's literally a page/component that is app.component.ts, so there is not any routing.
Use express.static() for serving static files.
It is because you have set a response of 'index.html' file for each and every request the server would receive. The first response would be good that's the index.html page only as expected. But, the index.html page must be having some script and css tags to fetch your Angular Javascript code which I assume would be on the same node server. So when the browser would encounter a line like:
<script src="/angularApp.js"></script>
..in your index.html file while parsing it, it would make another request to the node server for http://localhost:<port>/angularApp.js but would get the index.html file as the response as that is what you have set.
Do it like this to serve static files like .html, .css, .js or what have you:
app.use(express.static(path.join(__dirname, '/dist')));

Webpack + Express: How to serve static resources in /node_modules from the server

I am trying to use webpack to generated a bundle.js file for a node module. The bundle.js file will be used in the client browser.
Here is the problem, the project has some dependencies that use static files in the node_modules directory. For example, the path of one of the static file is
/node_modules/node-pogo-signature/lib/proto/Signature.proto
When I try to run the bundle.js file in the browser, I get this error
GET http://localhost:3000/proto/Signature.proto 404 (Not Found)
If I copy the the Signature.proto file into my /public folder, the bundle will then find it. However, manually copying static files from /node_modules to /public can be tedious and hard to maintain.
Is there a better way to do it?
var myfile = require('./node_modules/node-pogo-signature/lib/proto/Signature.proto');
Then you may add it to a route, for example if you use express this is how you can display the content of the package.json file:
// create a new express server
var express = require('express'); // We use express as web server http://expressjs.com
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("server started");
});
// Shows content of package.json
var myfile = require('./package.json');
app.get('/showfile', function (req, res){
if (debug) {
console.log("showfile received a request");
};
res.send(myfile);
});
You just have to add /showfile at the end of the url , for example : http://localhost:6006/showfile

serving a Single Page Angular App using Restify

I am new to AngularJs and wanted to start learning it. I was going to use Restify as my api/backend and was hoping it was possible to serve static files up for the route /.
app layout is something like this..
/nodesprinkler
node_modules/
public/
css/
main.css
bootstrap.css
js/
angular.js
app.js
...
img/
...
index.html
favicon.ico
server.js
routes.js
...
My server.js looks like so:
var restify = require('restify'),
app = module.exports = restify.createServer();
app.listen(8000, function() {
console.log('%s listening at %s', app.name, app.url);
});
/* Client Side Route */
app.get('/', restify.serveStatic({
directory: 'public',
default: 'index.html'
}));
module.exports.app = app;
routes = require('./routes');
How can i get Restify to serve up my static assets so it'll work like a regular express app works? I know restify is based off express, so there must be something simple that i'm missing. It will serve up / as index.html but any of my css and js files I dont have access to.
try express.static()
before app.listen put
app.use(express.static(__dirname+"/public"))
The docs
Try this:
app.get("/css|js|img/", restify.plugins.serveStatic({
directory: "./public"
}));
app.get(
"/.*/",
restify.plugins.serveStatic({
directory: "./public",
file: "index.html"
})
);
I'm creating my futur startup with the same technologies: Restify (that I rewrite) and Angular JS for the single app view.
I've tried of lots of solutions and the best one for me is :
Keep a WS with Restify (or what you want) WITHOUT any static files... I serve it with a dedicated server (python for dev, NGinx for production).
I know this is not the expected answer but give it a try.
python -m http.server on your angular directory is so simple :p

Resources