Static site with express using a public fonder - javascript

I think this is probably just a misunderstanding of how to do this on my part but its bugging me and I haven't found anything to answer the problem.
I have a static site where my file structure is
--node_modules
--index.html
--server.js
--app.js
my server.js is simple its just
var express = require("express");
var cors = require("cors");
var app = express();
app.use(cors());
app.use(express.static(__dirname + '/'));
app.get('/question', function(req, res){
res.send(req.body);
});
// Start the server on port 3000
app.listen(process.env.PORT || 3000);
// Print out a nice message so you know that the server started
console.log('Server running on port 3000');
and my bootstrap and angular WORKS...your probably wondering what the problem is....
So I have a 2nd site and I building and thought I would organize my stuff a little better. My file structure is
--node_modules
--public
|---index.html
|---app.js
--server.js
The only difference in my server.js is
app.use(express.static(__dirname + '/public'));
my bootstrap and angular is referenced in index.html like
<script src="../node_modules/angular/angular.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
This DOESN'T work!...now I know I could just do it the first way or use a CND but I was wondering if anyone could educate me as to why and what I am doing wrong.
All help and education is greatly appreciated.

Angular and Bootstrap probably shouldn't be in node_modules unless you are using Browserify. Express won't serve any static files that aren't under the express.static root, so you can't use ../ relative paths if they go higher than public/.
That is, you need to move everything that you want to be public somewhere under public/ including index.html and the JavaScript libraries you will use.

Related

Express.js just won't serve static files

I am trying desperately to get it working that my express server serves statics files but I just can't get it to work... I already tried multiple attempts at solving it but none of it worked.
So my folder structure is the following:
App
- Web
-- public
--- images
--- css
-- Server.js
The code from my server is the following
const express = require('express');
const app = express();
app.use('/static', express.static('./public'));
const server = app.listen(80, function() {
const host = server.address().address;
const port = server.address().port;
console.log(`Server is running on ${host}:${port}`);
});
It just won't serve the files..
No matter how I change the usage of the public folder. I already tried with path.join and __dirname but none of it worked. I only get the express error Cannot GET /static ...
This can happen when the current working directory is not what you think it is and hence ./public doesn't resolve to the right path. The safer way to do this is to use __dirname, the directory of the current file:
app.use('/static', express.static(path.join(__dirname, 'public')));

Why express api doesn't GET this folder?

I have a js script for a server is required to GET files from folder called "public". But when I go to localhost it says Cannot GET / .The script is:
const express = require('express');
const app = express();
app.use('/', express.static('/public'));
app.listen(3000);
I am really new to js, express api, and web dev in general so could anybody help me?
I can't add a comment since I don't have the rep, but judging by your other comments you want to change the /public to ./public

onload js call not working with node

I am starting to learn node.js, for now I am just trying to execute my old none node app with node. In this app, I have a html page with a body calling an onload js function. It's working just fine.
Now I have a a node app: app.js, simple as that:
var express = require ('express');
var app = express ();
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ketcher'));
app.use(express.static(__dirname +'/ChemAlive_JS'));
app.get('/', function(req, res) {
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/ChemAlive_Interface.html');
});
app.listen(8080);
And in the .html I still have:
<body onload="ketcher.init();">
but the function I want to load is not load at all anymore.
Any clue?
Thanks
You have not provided a lot of info in the question but from what you provide I can have few suggestions:
Suggestions
Instead of adding a lot of express.static uses:
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ketcher'));
app.use(express.static(__dirname +'/ChemAlive_JS'));
put those files (and directories) that you want to be served into one directory, e.g. called static, and use express.static once:
app.use(express.static(__dirname + '/static'));
or better yet, using the path module:
app.use(express.static(path.join(__dirname, 'static')));
you need to require the path module first with:
var path = require('path');
Now, instead of serving the single file for the '/' route with:
app.get('/', function(req, res) {
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/ChemAlive_Interface.html');
});
just put that file into the static directory as index.html so it will be served by the express.static middleware automatically.
Rationale
The way you have it configured currently, is that e.g. everyone can download your Node application - app.js with all of its configuration and even submodules etc.
Also, by using the express.static middleware many times I suspect that you are not sure how the files in those directories will be mapped to URLs.
Having a one place for static files makes it easy to verify whether any script tags have correct paths etc.
My guess
You don't provide enough info to be sure but my guess is that the JavaScript files for the main HTML file are not loaded correctly but you provide not enough info to be sure.
You can open the developer tools console in the browser and reload the page while the console is open and see for errors.
I suspect that the ketcher.init() method is being run but either the method, or the ketcher object is undefined, because some <script> tags failed to be loaded.
Example
The full example after following my suggestions would be much simpler:
var path = require('path');
var express = require ('express');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.listen(8080);
Maybe I would add some output to see what's going on:
var path = require('path');
var express = require ('express');
console.log('starting app.js');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.listen(8080, function () {
console.log('listening on http://localhost:8080/');
});
And now you will have all files that can be served to the browser in one place: in the static directory in this example.
Working app
You can see my example of a working Express application serving static files on GitHub:
https://github.com/rsp/node-express-static-example
In this example the directory for static files is called html but you can call it how you want, as long as it's consistent with how you use the express.static middleware.
You can start from this example project and just put your own files into the directory where express.static is told to look for files to serve.
You can also change the port number to match your needs.
More examples to do the same with and without Express, plus better explanation:
https://github.com/rsp/node-static-http-servers
More hints
The onload callback may not be fired if the page is waiting for some resources to load.
To see if your onload callback is firing you can change it to:
<body onload="alert('onload callback fired');">
Also the ketcher object may be not initialized or it may not have the init() method. After the page is loaded you can open the JavaScript Console and try running the method manually to see if it would work if it was fired:
ketcher.init();
You can also try commands like:
console.dir(ketcher.init);
console.dir(ketcher);
console.log(typeof ketcher.init);
console.log(typeof ketcher);
to see if the ketcher object contains what it should.
Even if the GET localhost:8080/ketcher.js gives a 200 OK status, it can still load some other resources that are not available or, as is very common with code that serve files with res.sendFile() (though unlikely in this case), it can serve HTML instead of JavaScript and result in a cryptic parse error on the < character - see this question for example:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 while acess static files in node server
Other related answers:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
Sending whole folder content to client with express
Loading partials fails on the server JS
Node JS not serving the static image

Heroku not loading js script 404

I am trying to build my first web app using MEAN on Heroku. I followed their guide to getting a sample app running. Then I downloaded the sample app code and altered it to load the login page. Unfortunately, I can't get the my app.js file to load. This is the angular script. In the main directory I have index.js that is running express. Anyways, I am able to get the .ejs .css and img files to load but this script wont. I am stuck. I need to be able to get past this to tinker enough to start learning the stack.
Script is in the public directory with the other files that get loaded. Code looks okay? Don't know why I get 404 on the script.
Any help is much appreciated!
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
response.render('pages/index');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
<script src="/js/app.js"></script>
Turns out changes weren't being pushed to the server. That's all folks!
You just need to move app.js to the public folder. This line app.use(express.static(__dirname + '/public')); in your index.js tells express to serve static assets out of the /public folder. Everything else in your project will be "hidden" on the server unless you expose it.
You could create a js folder in public and move app.js there. Then change the reference in index.ejs from src="/app.js" to src="/js/app.js".

How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

My express app serves an HTML page from my disk upon the initial GET (i.e., if I hit "http://localhost:3000/" in the browser). Now I would like to access a JavaScript file which is in the same location in the disk as the HTML file. When I try to include it in 'index.html' by using
<script src="/myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="./myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>
it doesn't work. The myJavaScriptFile.js file is never reached.
My express app looks like this:
var express = require('express')
var testMethod = require('./test')
var app = express()
app.use(bodyParser.urlencoded({ extended:false }));
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
app.get('/', function (req, res) {
console.log('In /');
res.sendFile(__dirname + '/index.html');
})
Express app is serving 'index.html' using the reference path '__dirname' + '/index.html' using res.sendFile function. (I am beginning to feel that this is a bad way of doing it. Please let me know if you think so too).
Also as we can see in the express app, an external JavaScript file called 'test' which is in the same location as 'index.html' and 'express.js' is being included without any issues. Could anyone please shed light on what's actually happening in the background? What exactly would be reference path for the JavaScript file that I can give in my 'index.html' if it is being served by express app? Thank you.
Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - express.static.
Pass the name of the directory, which is to be marked as the location of static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:
app.use(express.static('public'));
Now, you will be able to load the files under 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
More Detail Here
Happy Helping!

Categories