Sourcing files that are retrieved with app.get() - javascript

In Node.js, I'm routing different directories in a site and am using app.get() to redirect traffic.
Problem: When using app.get(), the index.html file that is sent to the user thinks its directory is the root directory. But I have libraries that are in the sub-directory that aren't being reached.
Example:
app.get('/htmlFileInD1', function(req, res){
res.sendFile(__dirname + '/root/D1/htmlFileInD1.html');
}
But in htmlFileInD1.html is:
<img class="wifi_battery" src="img/wifi_battery4.gif">
The image is being called from the root directory, but the img folder is in the D1 subdirectory.
I don't want to do:
<img class="wifi_battery" src="root/D1/img/wifi_battery4.gif">
since I have a lot of other libraries that I would have to change the source for.
What's the best way for the app.get() file to still call on its native directory?

You can serve your static assets like images by adding the following in your app
app.use(express.static(__dirname + '/root/D1/'));

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

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

How to send a lot of files from server to client using express (NodeJS)

I'm trying to send files from NodeJS server to clients. Many images, css files, js files. For a few files I use
app.get('/js/client.js', function (req, res) {
res.sendFile(path.join(__dirname, '/', 'client.js'));
});
The path is var path = require('path');
So, if I use this construction for every file I want to send, this part of the code will be huge. How can I simplify it?
If you want to serve static content, put all content in public folder in will be automatically served using express.
app.use(express.static( __dirname + "/public"));

Node js serving old versions of modified angular files (instead on new ones)

I'm programming a project using the MEAN stack. All fine, except with the static files.
I have some rules in the Node router file to serve the static files. And it's working, but then I have done a change on an Angular file, but the Node server is returning me the old version of this file (before the changes).
Why is this happening?
Mainly, my server routing code is this one:
var app = express();
app.use("/node_modules/angular", express.static(__dirname + '/node_modules/angular'));
app.use("/scripts", express.static(__dirname + '/public/scripts'));
app.get('*', function(req, res){
res.sendFile(path.join(__dirname + "/public/index.html"));
});
The problem is that express will cache your static files because they really shouldn't change like Yevgen said. It's why you'll often see stuff like mainSOMENUMBER.css in production. So everytime you update a resource file like main.css or in this case app.js you add a version number to it and then change the source.
Long story short here is your fix.
app.use("/node_modules/angular",
express.static(__dirname + '/node_modules/angular'){maxage: 0});
I guess you are using such setup only for development process. Ideally static file should never change, the new version of the file should be reflected in new file name. By default express static middleware servs the new version of the file without server restart. I could suggest in your case to setup nodemon or forever to watch on file changes in your static folder and trigger server restart.

Troubleshooting node.js error

I just inherited a node.js project, where I'm suspicious that some of the original boilerplate necessary for a node project hasn't been finished. This is also my first time using node.js.
Anyway, when I run node app.js, the correct port boots up and everything, but the app can't load a number of the script files (the error "Uncaught SyntaxError: Unexpected token <" is given on each js file unable to be loaded). I've tried to troubleshoot this error, there are a lot of resources online for it, but I haven't been able to nail it down. I tried adding type="text/javascript" to each of the script tabs but it didn't change anything.
When I click to troubleshoot the incorrect loading paths of the scripts, they all bring me to the index.html page. Thus, for some reason, it seems like this section of the code from the app.js file isn't working:
// serve all asset files from necessary directories
app.use('/js', express.static(__dirname + '/public/js'));
app.use('/css', express.static(__dirname + '/public/css'));
app.use('/partials', express.static(__dirname + '/public/partials'));
app.use('/lib', express.static(__dirname + '/public/lib'));
// JSON API
app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
app.all('/*', function(req, res, next) {
res.sendfile('index.html', { root: __dirname + '/public' });
});
However, it looks like it should be working properly (following the paths of the files). Any ideas?
Almost certainly the app.all route is sending back HTML for a request that should be sending javascript. You need to look at the specific URLs that the browser is fetching as script tags but the server is sending back HTML. The corresponding .js files probably are just not there under public/js which causes the router to proceed to the catch-all route.
Side note you can compress your express.static routes to just this because of how your URLs line up with the filesystem structure.
// serve all asset files from necessary directories
app.use(express.static(__dirname + '/public'));

Categories

Resources