Troubleshooting node.js error - javascript

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

Related

Express app.get() code in server not updating but other server code will update

I have a node js and express server I run on localhost. Recently, while changing the server code from
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
to
app.get('/', (req, res) => {
res.send('home');
});
The server still serves the "index.html" file and does not send the message "home". I also tried deleting all my "app.get()" and "app.post()" functions and it still runs as it was before the changes. I have double checked that I saved the file and restarted the server but even then, still does the same thing. The odd thing is that when changing anything else in the server code aside from my express code it runs as expected.
I tried searching my problem but no one is experiencing the same issues. Any help is appreciated, thanks.
All of your code is not listed, so this is an educated guess, but I would check to see if you are using express.static or another package to serve the directory your index.html file is in via app.use() before your routes. By default express.static will serve index.html if presented a root path ('/').

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

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.

Sourcing files that are retrieved with app.get()

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

exclude a folder from expressjs routing

On my expressjs app, public assets are loaded in this way:
app.use(express.static(__dirname + '/public'));
And then I redirect all requests to the index, to handle every path with Backbone
app.get('*', routes.index);
Why the /public folder is redirect too?
Also if i try to add '/public' as a first argument, it doesn't work:
app.use('/public', express.static(__dirname + '/public'));
For anyone who get any problem related to static files serving:
Before evaluating possible solutions to the problem, be sure to define express.static before the app.use(app.router).
I found lots of examples online: sometimes its defined below, sometimes not.
Putting it first solved all my problems.
app.use(express.static(path.join(__dirname + '/public')))
app.use(app.router)
After you placed the static router before app.router, express will attempt to serve requests first by matching a file from the static folder (public), if there's no match, it will pass it to routes.index as the following rule matches everything;
app.get('*', routes.index);
Also, to match any file from public dir, you need not use /public/ in the request url.
For example to fetch public/images/icon.png or public/js/scripts.js, you will only need to access /images/icon.png or /js/scripts.js. If you invoke a /public request, it will not match anything in static dir, and pass the request on to routes.index.
Hope it helps.

Categories

Resources