How to make express serve static files from another upper directory? - javascript

If I have an nodejs express application with folowing folder structure:
-src
- client
- public
- css
- js
- ...
- views
- server
- server.js
How can I serve the static files in the public folder from the server.js file, since it is located above the index.js root location?
How should the:
app.use(express.static();
look like?
----UPDATE---
SOLVED this by using:
app.use(express.static(path.join(__dirname, '/../client/public')));

Actually solved my problem by using:
app.use(express.static(path.join(__dirname, '/../client/public')));

You can use path.join()
app.use(express.static(path.join(__dirname,'public')));

just do this, (as per your directory structure)
app.use(express.static(path.join(__dirname, 'src/client/public')));
// http://localhost:3000/hello.html
or
app.use('/static', express.static(path.join(__dirname, 'src/client/public')))
// http://localhost:3000/static/hello.html

Related

Resolving dependencies in express server

I am having some trouble resolving dependencies on my express server.
Here is my project structure
Calculator
--dist
----app
-------calculator.js
-------server.js
--node_modules
--src
----app
--------calculator.js
--------server.js
----public
--------calculator.css
--------calculator.html
----.babelrc
----.gitignore
----package.json
Here is my server.js code
const express = require('express');
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(path.resolve('./src/public/calculator.html'));
});
app.use(express.static(__dirname + '../../src/app/public'));
app.use(express.static(__dirname + './'));
app.listen(3000, () => {
console.log(__dirname);
console.log("Listening on port 3000");
});
The reason I have a dist folder and a src folder is because I am compiling my JS from ES6 from the src folder to ES5 within the app folder using Babel.
However, when I launch my node server, my html is not able to load the css file and JS file. I am using these paths to load each respectively from the calculator.html file
<link rel="stylesheet" type="text/css" href="./calculator.css">
<script type="text/javascript" src="./calculator.js"></script>
I am sure I am missing something about the way files are served on a localhost. Would appreciate the error being pointed out.
It looks like on line 9 in server.js:
app.use(express.static(__dirname + '../../src/app/public'));
you're going from the app folder up to src, up to the root, back down into src, back into app, and then trying to go down into public. However by your project structure diagram, public isn't inside app but rather beside it. You'd want something more like app.use(express.static(__dirname + '../public')); In addition, I'd recommend using the path module that's built into Node. It'll make sure you don't have mistakes in path creation.
EDIT: Sorry, that was incorrect. I didn't see that you were transpiling your server code as well. You'll want to use these lines, which should fix both:
app.use(express.static(__dirname + '../../src/public'));
app.use(express.static(__dirname));
This is assuming you run the server.js file present in dist/app and not the one in src/app.
Alright, this worked for me although I'm not a 100% sure why exactly.
I set my express static file delivery to the following
app.use(express.static(__dirname + '/../../src/public'));
app.use(express.static(__dirname));
My __dirname was shown to be Calculator/dist/app so changing the src attributes for the CSS and JS in the HTML file to this worked
<link rel="stylesheet" type="text/css" href="./calculator.css">
<script type="text/javascript" src="./calculator.js"></script>
I am assuming this works because I set my express static folder to look inside the /src/public folder and since my current directory was the /dist/app folder, I could serve the JS file directly from there?
Try one of these ...
app.use(express.static(__dirname + '/./src/app/public'));
app.use('/', express.static(__dirname} + '/./src/app/public')); // __dirname doesn't include the ending back slash, I think?
The first will always look in your static directory, and the second will look in your static directory for '/' and below. See https://expressjs.com/en/4x/api.html#app.use for more.
And then ...
Change your HTML so the src attributes will be '/calculator.css', etc

client - server architecture structure (with node js) - where to put the index.html file?

I have built a server client app (nodejs - on the server, angular - on the client).
I used to have all my code in one project (one folder) but then I figured it makes more sense for me to divide it, by logic, to a server folder and to a client folder.
I aspire for disconnecting all of the dependencies between the server code and the client code, in the sense that each side can stand alone by its own.
Questions:
where do I put the index.html?
it is obviously related to the client side but the server (expressJS) is loading it when the server.
lets says I put this index.html file in the client folder like in the picture below..
how can I make the server.js be aware of it?
this code doesn't work:
var app = express();
app.use(bodyParser.json());
app.use('/',express.static(__dirname));
app.use('/scripts', express.static(path.join(__dirname,
'node_modules')));
app.get('/', function (req, res) {
res.sendFile(express.static(path.join(__dirname + '../client/index.html')));
});
Usually with express apps, you would have a "public" folder that contains your client assets, index.html being one of them.
app.use('/',express.static(path.join(__dirname, '/public')));
then, run the node server, open a browser and point it to that server and express will serve up "index.html" from the "public" folder.
Steps to fix
Rename client folder to public
Drag public inside server folder so its like server/public
change app.use('/',express.static(__dirname)); to app.use('/', express.static(path.join(__dirname, '/public')));
Please note: app.use('/',express.static(__dirname)); should be avoided, you're serving up your whole server directory to the public.
If you want to have a better look at project layouts.
Have a look at yoeman.io, specifically it has project templates for express.
http://yeoman.io/
Yeoman helps you to kickstart new projects, prescribing best practices
and tools to help you stay productive.
var app = express();
app.use(bodyParser.json());
app.use('/',express.static(__dirname));
//it will serve all files in client directory under the '/' route
app.use('/', express.static(path.join(__dirname, '/client'));
});
//and the client side scripts installed through npm will be served under '/scripts' route
app.use('/scripts', express.static(path.join(__dirname, '/client/node_modules')))
It will be good to serve the client side modules in separate folder i.e. to have node_module folder in the client directory as well, there you should install all modules which should be load from the client side. Besides this the client folder seems public, so it is worth to serve the whole folder.
If you want to install modules for client side then go to '/client/node_modules' directory in the terminal and run the npm. So if you are linux, then:
cd client/
npm init
npm install YOUR_DESIRED_MODULE
In case of modules for server side install modules in your root directory

Path broke in Nodejs

I have a problem from client side with my path for a image or css, my image and css are in the same folder with index.html but index don't see it.
My folder structure:
index.html
image.jpeg
main.css
server.js
In index.html I ask the path for image and css so:
<img src="/image.jpeg">
<link rel="stylesheet" type="text/css" href="/main.css">
In server.js I ask the path for index so:
var app = require('express')();
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
Read Express docs before use it: serving static files in Express
You problem is that you have no way of serving static files.
Include this:
app.use(express.static(__dirname + '/public'));
And use the directory 'public' to store your files.
There is a question posted here that is similar to yours and which may provide further clarification. Basic webserver with node.js and express for serving html file and assets

Having all website paths load the same static website in express

In my express server, I want to have all paths load the same static website, which I tried doing with the following code:
const express = require('express');
const app = express();
app.use('*', express.static('build'));
app.listen(3000);
Unfortunately I am presented with the following console errors when I navigate to any path on localhost:
:3000/main.js/:1 Uncaught SyntaxError: Unexpected token <
When attempting to view the JS file with the error, it seems to be serving index.html in its place.
I know this is due to the wildcard, but I can't think of a way to cleanly exclude all file names and paths from the static server.
I think you're looking for something a little more like this..app.use(express.static('public')
if your tree looks like
ProjectName
| server.js
| public
| index.html
you don't need the * as a parameter since setting the express.static sets the folder open to public view. This is how you separate your server code and client code. Be careful not to expose your entire project directory as people will then have access to your server code. This is why you're client files should be kept in a public folder or a www folder (common practices)
--EDIT
//this will server css, and js files so they can be linked into the html
app.use(express.static(__dirname + '/public'));
//this will force all url's except the public files to be given the index.html file.
app.use('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});

Express JS: Can I still have <scripts> in my index.html

When converting an index.html page to be served up by Express, instead of Webstorm, I noticed that all my scripts suddenly reported 404 - Not Found, where previously they were found just fine.
Should I not be serving up a page from Express that has a bunch of tags? If it is OK to do so, how come they are all 404-Not found now, where previously they were found just fine?
EDIT: Directory structure:
project
--- src
--- js
main.js
--- css
index.html
app.js <-- all the express code
Express code includes these lines:
app.use(express.static(__dirname + '/js'));
app.use(express.static(__dirname + '/css'));
Make sure Express is set up to serve your static assets. By default it will serve these from /public
app.use(express.static(path.join(__dirname, 'public')));
You can add your scripts there (recommended!) or add additional express.static statements pointing to your specific scripts folder.

Categories

Resources