Node.js and Express: "Cannot GET /" static site - node.js

I'm working on a small Node app and things were working fine. It needs to serve some static files from a directory /source.
Today, after a computer restart, when I visit my local site all I get is Cannot GET /. Nothing in the Node config has changed since it was working last.
var express = require('express'),
app = express(),
path = require('path'),
fs = require('fs');
// Load our static site to start with
app.use(express.static(path.join(__dirname, 'source')));
// Start the node server
app.listen(3000, function() {
var host = this.address().address,
port = this.address().port;
console.log('Serving Atenium at http://%s:%s', host, port);
});
My folders look like:
|- app/
|-- index.js
|- source/
|-- <static files>
Any ideas as to why this just stopped working?

Could you have updated your express module in the process? I believe in Express 4, static content is now handled by the serve-static middleware library found here https://github.com/expressjs/serve-static .

Instead of using
app.use(express.static(path.join(__dirname, 'source')));
you have to create a virtual static path like:
app.use('/source', express.static(path.join(__dirname, 'source')));

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.

node express cannot GET static content

Im running a node app inside of /opt/myapp directory.
I have haproxy in front content switching on path_beg /myapp
backend server is listening on port 3000
directory structure:
/opt/myapp
index.js
package, modules
static
public
myfile.html
const express = require("express");
const path = require('path');
const app = express();
app.listen(3000, () => console.log("listening on 3000 "+__dirname+" "+process.cwd()));
app.use(express.static(__dirname+'/static/public')); //nope
//app.use(express.static('..'+'/static/public')); //nope
//app.use(express.static(path.join(__dirname, '/static/public/'))); //nope
Where __dirname outputs /opt/myapp and process.cwd() outputs /opt/myapp
I tried both concantenation and path.join with same results. Cannot GET myfile.html
curl directly on the server to http://host.com:3000 does work by returning the page,
but from browser (in front of haproxy), http://host.com/myapp/myfile.html does not work.
I suppose that I can remove the /myapp from the path in haproxy on the backend, but is there a way with express that i can account for the base directory?
This worked:
app.use('/myapp/',express.static('static/public'));

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

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