Subdirectories not being served with express.static in heroku - node.js

I'm seeing some really odd behavior where some of my files are correctly being returned by my express/node server (using express.static()), but not files within subdirectories. The frustrating thing is that it works fine using node or foreman locally, it just won't work on heroku. This gist has the main files at play here, and my app structure looks like this:
-app
- index.html
- img/
- base.png
- sub/
- sub.png
- scripts
- base.js
- sub/
- sub.js
- css
- base.css
- sub/
- sub.css
- server
- app.js
The index.html, and base.* files all load fine, it's just the sub.* files that 404. Seems bizarre that express.static would go 1 level deep, but not 2
I've tried a slew of different configurations, including this stackoverflow answer. I have to be missing something simple. Thanks for the help.
UPDATE:
When I console.log the following on server startup on heroku, I get:
path.join(__dirname, '../app') = /app
path.join(__dirname, '/../app') = /app/app
path.normalize(path.join(__dirname, '../app')) = /app/app
path.join(process.cwd(), '../app') = /app/app

Make sure that the sub directories of your directory are added to your Git repository.
You can use heroku run 'ls ~' to help debug the issue (by observing the files on the dyno).
Putting the absolute path did not fix it for me. Your .gitignore may be excluding it.

Try changing your static dir to :
app.use(express.static(path.join(__dirname, '/../app'), { maxAge: 86400000 }));
or
app.use(express.static(path.normalize(path.join(__dirname, '../app')), { maxAge: 86400000 }));

add {{__dirname}}
<link href="{{__dirname}}/stylesheets/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
in your layout.hbs or layout.jde

I've just had the same issue, and I've read all the different answers, some of which may have been important, but, in the end, this is the change I made after which the static content started getting served.
CALENDARSPATH = path.join(process.env.PWD, 'calendars');
...
-app.use(express.static(CALENDARSPATH, { maxAge: 86400000 }));
+app.use('/calendars', express.static(CALENDARSPATH, { maxAge: 86400000 }));

Related

How can I change the name of the _nuxt folder?

Hello I've got an issue with a Nuxt.js app that I can't seem to resolve. What I want to do is to change the name of the generated _nuxt folder with some other name. So far I've updated the nuxt.config.js and added this snippet:
build: {
publicPath: '/new-folder'
},
as far as I understand this publicPath variable expects a CDN link so probably this is not the correct way of changing the default _nuxt folder name.
I have also tried adding the buildDir: 'new-folder but when I run the build command it doesn't show up in the project. No matter what changes I added in the nuxt.config file when I deployed it on heroku all the assets where still in the _nuxt folder which causes issues to my project. Am I not seeing something am I doing something wrong?
Since the default answer in nuxt JS Documentation is /_nuxt/. The correct answer should be /yourCustomName/ - be ware that you need two forward slash.
In nuxt.config.js
build: {
publicPath: '/customName/'
}
t's simple, just change in build the publicPath.
buildDir is to change the folder for development, where the files will be when coding
nuxt.config.js:
build: {
publicPath: 'new-folder/',
},
in my case, my publicPath is leo/
you can check more about it here:
https://medium.com/#andrejsabrickis/how-to-set-custom-configuration-for-nuxt-js-generate-task-5055e53c2da5

How to configure the page the / path goes to in a tiny express app?

I'm using a simple node express server which is wrapped in the Webpack Dev Server (http://webpack.github.io/docs/webpack-dev-server.html)
I'm starting an express app from a top level directory where the static files are in a directory called "public".
I've got this line of configuration:
server.app.use(express.static(__dirname + '/public'));
If I type http://0.0.0.0:3000/index.html, all is good.
How but the URL of http://0.0.0.0:3000/ produces a directory listing of the top level.
What is the proper way to configure http://0.0.0.0:3000/ to go to the index.html file?
add
server.app.get('/', function(req, res) {
res.sendFile('index.html');
});
See the docs http://devdocs.io/express/index#res.sendFile
The solution involved setting the contentBase proper of the WebpackDevServer plus telling the
server.app.use(express.static(__dirname + contentbase);
Per this diff
The docs are here: http://webpack.github.io/docs/webpack-dev-server.html

Automagic compilation of SASS with Express

I'm getting used to Express and various other node-related frameworks as I find it interesting and more lightweight than the ASP MVC world.. and one of the first things I'm trying to do is get SASS files automagically compiling into CSS files.
I've gotten some ways into it and installed node-sass and followed a few tutorials but I'm not quite getting the result I want. First of all, here is my directory structure.
app.js
static/
stylesheets/
images/
js/
sass/
index.sass
views/
index.jade
So my plan is fairly simple: when I visit views/index.jade in the browser, I want index.jade to render static/stylesheets/index.css - obviously, this doesn't exist at compile time, but we have the corresponding index.scss file inside of sass.
My set up currently is that /css/index.css will refer to __dirname/static/stylesheets. So, inside of my jade view, I have the following block:
block head
link(href='/css/index.css', rel='stylesheet')
The intention is that this link will refer to the compiled sass file. Here's the portion of app.js concerning the compilaton of sass and serving of static content:
// Enable SASS compilation
app.use(sass.middleware({
src: __dirname + '/sass',
dest: __dirname + '/static/stylesheets',
debug: true,
outputStyle: 'compressed'
}));
// Add static content
app.use('/js', express.static(__dirname + '/static/js'));
app.use('/img', express.static(__dirname + '/static/img'));
app.use('/css', express.static(__dirname + '/static/stylesheets'));
My issue is that what's actually happening is that SASS appears to be compiling the css just fine, but it's prepending everything into a /css/ folder (which doesn't exist) because of the /css route I've used above. Maybe the debug output will make more sense:
source : E:\project\sass\css\index.scss
dest : E:\project\static\stylesheets\css\index.css
read : E:\project\static\stylesheets\css\index.css
Obviously, this is not intended, and ends up 404ing as the browser thinks we are requesting css/index.css but the SASS file is being compiled into, effectively, css/css/index.css.
What should I do here? I assume I am making a glaring mistake but I can't see it as I am new to node/express.
I fixed this by changing the extension of my sass file to scss. That was the only issue. |: slightly annoying given that the package is named node-sass.

Node.JS express compile less in different folder

I need to compile *.less files in different folder inside public directory. I've git this dir structure:
/public:
/stylesheets:
/less:
style.less
/css:
style.css
/js
/img
...
In my app configure function I've got following:
app.use(require('less-middleware')({
src: '/less',
dest: '/css',
root: path.join(process.cwd(), 'public/stylesheets')
}));
app.use(express["static"](path.join(process.cwd(), 'public')));
But It does't work. Less files never compiles in css folder. Whats wrong?
PS: I could access to the less folder via path: /stylesheets/less/style.less. But why? Why not just /less/style.less? Thanks for any help!

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