ENOENT: no such file or directory, stat ERROR with Express Middleware - node.js

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);

Related

express.static files dont load static files

I am trying to server static files with express and them dont work, i think its express problem or something but i dont realize why it dont works.
my folders look like this:
app.js
public
--css
--js
--images
and the code i trying to run like this:
app.use(express.static(path.join(__dirname,'public')));
if i do console.log of the path
console.log(path.join(__dirname, 'public'))
i get the next path
C:\Users\J\Desktop\node.js\social-media-cars\public
and if i look at the path with the windows file explorer i see that the path is correct and i see the content inside, so i dont think its path fault
i also tryed :
app.use(express.static(path.join(__dirname,'public')));
app.use('/static',express.static(path.join(__dirname, '/public')));
and dont works, always the same things:
im desesparate with this, idk why this dont works.
code where i use it looks like this:
// Import the express module
const path = require('path');
const express = require("express");
// Instantiate an Express application
const app = express();
const dotenv = require("dotenv").config();
const ActionsRouter = require('./routers/actions-router');
const UserRouter = require('./routers/user-router');
const cookieparser = require('cookie-parser');
// app.use('/static',express.static(path.join(__dirname, '/public')));
//set static files that are rendered after
app.use(express.static(path.join(__dirname,'public')));
//read the cookies from response
app.use(cookieparser(path.join(__dirname, '/public')));
console.log(path.join(__dirname, 'public'))
//create the req.body
app.use(express.json());
//user
app.use("/api",UserRouter);
app.use("/useractions",ActionsRouter);
module.exports = app;
const server = app.listen(port,()=>{
console.log(`listening on port ${port}`)});
get the static files with every response i get
also i get this error
1. Add this middleware in the index.js or app.js above you set view engine
app.use(express.static(path.join(__dirname, "public")));
2. Folder Structure
|__public/
|__ css/
|__ css files...
|__ js/
|__ js files...
3. Import this way
Now you set the path to the public directory you have to give the path public folder when you import
<link rel="stylesheet" href="/css/main.css" />
In the same way, you can import your JS files
You should now be all set up to access CSS or js as well as any file in the public directory
okey i found it, i was so lost because when i try to see the files that i got in each response on the browser, i was not getting any file,
but only when i linked css and html it downloaded the static file, idk why this works like this,
i supposed every of /public file was atached to the response you use it or not
<link rel="stylesheet" type="text/css" href="/css/styles.css">
anyway if there is a way to get the file you request or not i would like to know

How to serve static files from root path '/'

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

Serving a Create-React-App application with a Node/Express router module

I'm fairly new to CRA, and normally I just use regular React with Webpack. I'm trying to serve my CRA just like I would any other React apps. My root directory file structure currently looks something like this:
controllers/
build/
app.js
package.json
Where "app.js" is my Node/Express server, build/ is the build folder for my CRA application (the index.hmtl, static directory, manifest, etc. are all here), and controllers/ is my router files. The router file I have to serve my react, called "staticController.js", is in the controllers/ directory and looks like this:
const express = require("express");
const path = require("path");
const router = express.Router();
router.get("/client/static/home", (req, res) => {
res.sendFile(path.join(__dirname, ".." , "/build/index.html"));
})
module.exports = router;
I import this router module into app.js to use it, and run the router on port 3001. When I go to localhost:3001/client/static/home, I get a blank page and an error saying:
GET http://localhost:3001/static/css/1.1ee5c864.chunk.css
net::ERR_ABORTED 404 (Not Found)
I'm not sure how to specifiy to CRA that the static directory and all associated build files should be under the "build/" directory. So instead, I move the static folder outside the build directory, into the root directory. The file structure looks like this now:
controllers/
build/
static/
app.js
package.json
When I try the route again, I still get the same error. Now I'm a bit confused as to how Node file structure works. If app.js is in the root directory, wouldn't localhost:3001/static/ just be my static/ folder? Why can't the CRA app find this folder?
use
express.static
to serve the build folder (or any static files)
e.g. : here i'm serving the build folder on the root path (assuming it's located on the same directory as the server file)
app.use('/', express.static('build'));
I believe what you are looking for is static.
https://expressjs.com/en/4x/api.html#express.static
You need something like
var express = require('express');
var app = express();
app.use(express.static('static'));

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')));

Express-js can't GET my static files, why?

I've reduced my code to the simplest express-js app I could make:
var express = require("express"),
app = express.createServer();
app.use(express.static(__dirname + '/styles'));
app.listen(3001);
My directory look like this:
static_file.js
/styles
default.css
Yet when I access http://localhost:3001/styles/default.css I get the following error:
Cannot GET / styles /
default.css
I'm using express 2.3.3 and node 0.4.7. What am I doing wrong?
Try http://localhost:3001/default.css.
To have /styles in your request URL, use:
app.use("/styles", express.static(__dirname + '/styles'));
Look at the examples on this page:
//Serve static content for the app from the "public" directory in the application directory.
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
I have the same problem. I have resolved the problem with following code:
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));
Static request example:
http://pruebaexpress.lite.c9.io/js/socket.io.js
I need a more simple solution. Does it exist?
This work for me:
app.use('*/css',express.static('public/css'));
app.use('*/js',express.static('public/js'));
app.use('*/images',express.static('public/images'));
default.css should be available at http://localhost:3001/default.css
The styles in app.use(express.static(__dirname + '/styles')); just tells express to look in the styles directory for a static file to serve. It doesn't (confusingly) then form part of the path it is available on.
In your server.js :
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/public'));
You have declared express and app separately, create a folder named 'public' or as you like, and yet you can access to these folder. In your template src, you have added the relative path from /public (or the name of your folder destiny to static files). Beware of the bars on the routes.
I am using Bootstrap CSS, JS and Fonts in my application. I created a folder called asset in root directory of the app and place all these folder inside it. Then in server file added following line:
app.use("/asset",express.static("asset"));
This line enables me to load the files that are in the asset directory from the /asset path prefix like: http://localhost:3000/asset/css/bootstrap.min.css.
Now in the views I can simply include CSS and JS like below:
<link href="/asset/css/bootstrap.min.css" rel="stylesheet">
What worked for me is:
Instead of writing app.use(express.static(__dirname + 'public/images')); in your app.js
Simply write
app.use(express.static('public/images'));
i.e remove the root directory name in the path. And then you can use the static path effectively in other js files, For example:
<img src="/images/misc/background.jpg">
Hope this helps :)
to serve static files (css,images,js files)just two steps:
pass the directory of css files to built in middleware express.static
var express = require('express');
var app = express();
/*public is folder in my project directory contains three folders
css,image,js
*/
//css =>folder contains css file
//image=>folder contains images
//js =>folder contains javascript files
app.use(express.static( 'public/css'));
to access css files or images just type in url http://localhost:port/filename.css ex:http://localhost:8081/bootstrap.css
note: to link css files to html just type<link href="file_name.css" rel="stylesheet">
if i write this code
var express = require('express');
var app = express();
app.use('/css',express.static( 'public/css'));
to access the static files just type in url:localhost:port/css/filename.css
ex:http://localhost:8081/css/bootstrap.css
note to link css files with html just add the following line
<link href="css/file_name.css" rel="stylesheet">
this one worked for me
app.use(express.static(path.join(__dirname, 'public')));
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/shopping-cart/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/shopping-cart/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/user/stylesheets',express.static(path.join(__dirname, 'public/stylesheets')));
app.use('/user/javascripts',express.static(path.join(__dirname, 'public/javascripts')));
Webpack makes things awkward
As a supplement to all the other already existing solutions:
First things first: If you base the paths of your files and directories on the cwd (current working directory), things should work as usual, as the cwd is the folder where you were when you started node (or npm start, yarn run etc).
However...
If you are using webpack, __dirname behavior will be very different, depending on your node.__dirname settings, and your webpack version:
In Webpack v4, the default behavior for __dirname is just /, as documented here.
In this case, you usually want to add this to your config which makes it act like the default in v5, that is __filename and __dirname now behave as-is but for the output file:
module.exports = {
// ...
node: {
// generate actual output file information
// see: https://webpack.js.org/configuration/node/#node__filename
__dirname: false,
__filename: false,
}
};
This has also been discussed here.
In Webpack v5, per the documentation here, the default is already for __filename and __dirname to behave as-is but for the output file, thereby achieving the same result as the config change for v4.
Example
For example, let's say:
you want to add the static public folder
it is located next to your output (usually dist) folder, and you have no sub-folders in dist, it's probably going to look like this
const ServerRoot = path.resolve(__dirname /** dist */, '..');
// ...
app.use(express.static(path.join(ServerRoot, 'public'))
(important: again, this is independent of where your source file is, only looks at where your output files are!)
More advanced Webpack scenarios
Things get more complicated if you have multiple entry points in different output directories, as the __dirname for the same file might be different for output file (that is each file in entry), depending on the location of the output file that this source file was merged into, and what's worse, the same source file might be merged into multiple different output files.
You probably want to avoid this kind of scenario scenario, or, if you cannot avoid it, use Webpack to manage and infuse the correct paths for you, possibly via the DefinePlugin or the EnvironmentPlugin.
The problem with serving __dirname is that __dirname returns the path of the current file, not the project's file.
Also, if you use a dynamic header, each page will look for the static files in a different path and it won't work.
The best, for me, is to substitute __dirname for process.cwd() which ALWAYS donates the path to the project file.
app.use(express.static(process.cwd() + '/public'));
And in your project:
link rel="stylesheet" href="/styles/default.css"
See: What's the difference between process.cwd() vs __dirname?
I was using
app.use(express.static('public'))
When there was no file in the public folder with name index.html.
I was getting the following error in the browser:
"Cannot GET /"
When I renamed the file to 'index.html', it works fine.
Try accessing it with http://localhost:3001/default.css.
app.use(express.static(__dirname + '/styles'));
You are actually giving it the name of folder i.e. styles not your suburl.
I find my css file and add a route to it:
app.get('/css/MyCSS.css', function(req, res){
res.sendFile(__dirname + '/public/css/MyCSS.css');
});
Then it seems to work.
if your setup
myApp
|
|__ public
| |
| |__ stylesheets
| | |
| | |__ style.css
| |
| |___ img
| |
| |__ logo.png
|
|__ app.js
then,
put in app.js
app.use('/static', express.static('public'));
and refer to your style.css: (in some .pug file):
link(rel='stylesheet', href='/static/stylesheets/style.css')
Try './public' instead of __dirname + '/public'.
Similarly, try process.cwd() + '/public'.
Sometimes we lose track of the directories we are working with, its good to avoid assuming that files are located where we are telling express where they are.
Similarly, avoid assuming that in the depths of dependencies the path is being interpreted the same way at every level.
app.use(express.static(__dirname+'/'));
This worked for me, I tried using a public directory but it didn't work.
But in this case, we give access to the whole static files in the directory, hope it helps!
In addition to above, make sure the static file path begins with / (ex... /assets/css)... to serve static files in any directory above the main directory (/main)
Create a folder with 'public' name in Nodejs project
folder.
Put index.html file into of Nodejs project folder.
Put all script and css file into public
folder.
Use app.use( express.static('public'));
and in index.html correct path of scripts to <script type="text/javascript" src="/javasrc/example.js"></script>
And Now all things work fine.
static directory
check the above image(static directory) for dir structure
const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))
// or
app.use("/", express.static(publicDirectoryPath))
app.use((req, res, next) => {
res.sendFile(path.join(publicDirectoryPath,'index.html'))
In your nodejs file
const express = require('express');
const app = express();
app.use('/static', express.static('path_to_static_folder'));
In your pug file
...
script(type="text/javascript", src="static/your_javascript_filename")
...
Note the "static" word. It must be same in nodejs file and pug file.
i just try this code and working
const exp = require('express');
const app = exp();
app.use(exp.static("public"));
and working,
before (not working) :
const express = require('express');
const app = express();
app.use(express.static("public"));
just try

Resources