How to serve static files from root path '/' - node.js

I understand that Express needs to be told where to serve static files from using something like server.use(express.static('public'); if all your static files reside in the public folder.
However there are static files in my app which MUST be served from the root of the site e.g.
http://example.com/ads.txt
http://example.com/sitemap.xml
http://example.com/app.webmanifest
I cannot create a separate route for each static file in the root folder because there can be many. When they are bundled up into the dist folder for deployment, they reside in the root of the site alongside the package.json file etc.
How can it be possible to serve the app's homepage at the route of '/' and also static files from that same route? e.g.:
server.use('/', express.static('/client'));
server.get('/', async (req, res) => {
// serve homepage here
})

var app = express()
app.use(express.static('folder_name'))
Or
app.use(express.static(__dirname + '/folder_mame'));
app.set('folder_name', __dirname);

According to official docs:
Serving static files in Express
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express static.
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Serving static files Express

Related

Why does my NodeJS Express app serve the entire website when sendFile() only contains path to one particular html file on the website

my directories are as follows
//SE-Metro-Q
...<other files>
...contact.html
//SE-Metro-Q-Private
...server.js
Each directory is a separate set of webpages in their own website, and from a webpage in SE-Metro-Q-Private, I am redirecting to a webpage in SE-Metro-Q in a get request.
I have the following middleware:
app.use("/contactForm", express.static(path.join(__dirname, '/../SE-Metro-Q')));
And then the route:
app.get('/contactForm', (req, res) => {
res.sendFile('contact.html', { root: path.join(__dirname, '/../SE-Metro-Q') });
})
From what I understand when I go to /contactForm on the browser, it should only load contact.html, but instead it loads index.html from the SE-Metro-Q directory specified in the middleware above.
How can I modify it to only load contact.html?
express.static() serves a directory of static files; you've mounted your local path /../SE-Metro-Q to the /contactForm route. As such, Express will serve the entire directory off the /contactForm route.
If you want to only serve one file, remove your express.static() route entirely and explicitly respond with the file you want to serve on that route, just as you have in your second snippet.

Serving express static files issue

I am having issues w/ serving static files in my current Express app, although I've done a similar setup in a bunch of other apps.. My folder structure is as follows:
/rootfolder/
/app
package.json
/client
/dist
/static
index.html
/server
/src
index.js
Relevant part of my server/src/index.js:
app.use(express.static(path.join(__dirname, "client", "dist")));
Where __dirname = /rootfolder/app/server/src
And when the user hits the / endpoint:
app.get("/", (req, res) => {
res.sendFile(appRoot.path + "/client/dist/index.html");
});
Where appRoot.path = /rootfolder/app
When I hit the / endpoint, I get a status 200 with the following text:
/rootfolder/app/client/dist/index.html
From what I can tell, the files are coded relative to each other correctly.. Does anyone know what I might be doing wrong?
Thanks in advance!
You're using res.send() instead of res.sendFile()
Also I suggest resolving your path via the path module, instead of concatenating a string.
const path = require('path')
app.use(express.static(path.join(__dirname, 'client', 'dist', 'static')))
And for the response of /:
res.sendFile(path.join(__dirname, 'client', 'dist', 'index.html')))
Try
app.use(express.static(path.join(__dirname,'client','dist')));
It basically gets the root directory and combines it with /client+ /dist + /static to give you the full route, without being relative path.
Now Let's call rootdirectory/client/dist X. That is the main directory for static files
If you have other files that are static but not in the same folder, you will have to give relative path from the X directory
Example:
app.get('/',function(req,res){
res.sendFile('/static/data.txt');
}
In the example above you indicate that the static file(data.txt) is located in the X/static directory.
Therefore => rootDirectory/client/dist/static/data.txt
2nd Example:
Let's say you have a folder in dist called images which you want to only store images.
when you are giving routes, you MUST use /images/filename.extention

express not sending static directory

I'm trying to serve a vue.js single page app with a node.js server but I'm having an issue with some express middleware.
Basically I'm trying to serve two things right now. My index.html and a dist folder that holds all of my static files. On localhost my index.html is served correctly but I'm getting a GET error for my dist folder and can not find it in the sources tab.
I've used more or less this same line of code for many single page apps before to serve my static assets but for some reason with this set up it's not serving the dist folder.
app.use(express.static(path.join(__dirname, '/dist')));
Anyone with express experience know why this line isn't working?
You are using express.static incorrectly. By default, express.static will serve the content you have INSIDE of that dist folder.
What you want to do is this:
app.use('/dist', express.static(path.join(__dirname, '/dist')));
This will force express to serve those static assets under the '/dist' route.

ENOENT: no such file or directory, stat ERROR with Express Middleware

This seems to be a common error with file paths but my problem is a but more strange because code worked fine yesterday but not today (and I did not change any code). My folder directory is quite simple:
-node_modules
-public
-css
-js
control_panel.html
index.html
app.js
packages.json
and I am using an Express middleware inside app.js to help render files.
var express = require("express");
var app = express();
app.use(express.static("public"));
app.get('/', function get(req, res) {
res.sendFile('/index.html');
});
app.get('/control_panel', function get(req, res) {
res.sendFile('/control_panel.html');
});
When I try to open index.html in the browser, there is no problem, everything works as expected. When I try to open control_panel.html in the browser, however, I get Error: ENOENT: no such file or directory, stat '/control_panel.html' at Error (native)
What is causing the problem?
A number of relevant points based on your situation:
All static assets (html files, images, CSS files, client-side script files, etc...) should be serviced automatically with an appropriate express.static(...) statement. You should not be creating individual routes for static resources.
To make express.static() work properly, you must locate all your static resources in a directory hierarchy that contains only files meant to be public.
Your private server-side files such as app.js should not be in that public directory hierarchy. They should be elsewhere.
Your path to express.static() is not correct.
Your path for res.sendFile() is not correct.
What I would suggest you do to fix things is the following:
Move app.js out of the public directory. It needs to be in a private directory. I'd suggest the public directory be a sub-directory from where app.js is located.
Then, your express.static() in app.js will work property to serve your static HTML fiels.
Then, you can remove the two routes you have for index.html and control_panel.html because express.static() should be serving them.
Here's one hierarchy that would work:
server
app.js
public
index.html
control_panel.html
And, an app.js like this:
var express = require("express");
var app = express();
// serve static files found in the public sub-directory automatically
app.use(express.static("public"));
app.listen(80);

Static Relative Files Not Found with Express `sendFile()` and Custom Root

I'm trying to serve a static folder, when using dynamic routes, by using res.sendFile() in ExpressJS:
res.sendFile('index.html', { root : path.join(__dirname, 'myStaticContentFolder') });
The file .../myStaticContentFolder/index.html, indeed gets served - hence: the root field correctly adjusts the path to it.
However, all the files within that folder, with paths relative to index.html are not found.
They are searched relative to the URL root instead of the root field path.
Note that the folder is properly served if I use:
app.use('/foo/', express.static(__dirname + '/myStaticContentFolder'));

Resources