Loading scripts in a Node app - javascript

This is my folder structure:
- getable_challenge
- node_modules
- stuff
- main.html
- main.js
- backend.js
- README.md
I want to load main.js from within main.html. Previously I had been accessing the page using the URL of file:///Users/adamzerner/code/getable_challenge/main.html, and a simple <script src="main.js"></script> allowed me to load the script.
But then I set up a Node server, at localhost:3000, and now it won't load the script. It's trying to load localhost:3000/main.js, which presumably is the wrong path. I'm not sure how to structure this... what should I do?
Server code (essentially)
var express = require('express');
var app = express();
app.listen(3000);

When you use the "file" protocol like that you aren't even using the web app to serve the script, you are directly accessing it on the local file system. That works fine when you are just running your app on your local machine but it completely breaks when you try to run it as a real app since the browser will have no idea where "file:///..." is, or even have permission to access it.
You need to put the client side scripts into a separate directory, usually named 'public', and then make your application aware of it. If you're using express you would do this:
app.use(express.static(__dirname + '/public'));
You want to put your statically served scripts ("public") into a separate directory so as to control access by your clients. If you just put them into the main directory and made the main directory accessible you could expose all your other files to public view, such as config files that sometimes contain passwords.
It also makes your structure much cleaner.

Try adding this line after var app
app.use(express.static(__dirname));
This should make your resources that are within your servers folder accessible. the var __dirname is the path to where your server is executed.

Related

Nuxt SPA without node server

I head to create Nuxt SPA with routing and mb API in future like that:
Backend server (on express or smth else) listen and on request give entire SPA to client.
Now user can use everything on client side (include routing) with no more else requests to backend (mb API requests only)
It means that server should give some .html file with js and css files as SPA and it will work on client side.
I tried to run some commands like nuxt build and nuxt generate
It looks like they return a same result - js files couldn't be found
And index.html file doesn't work properly
After some researching I found a solution
But now I got this:
It can't open the fourth js file in another js file. Path isn't right!
Every time I tried to run it as a static html file and from localhost (and also with using Live Server)
I think I did a lot of crutches and there should be another built-in function or feature that allows us to do what I want
I wrote a lot - if I made a mistake or you didn't get smth - please, ask! I need any help
To test your locally built application, you need to serve all files within the generated /dist folder. You can setup very easily a local web server using Express/Node.js as you already have Node.js installed when running Nuxt. Create a new folder and install express via npm (run npm install express).
Then, copy everything from /dist into /public and create a file server.js:
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000);
Run the web server with node server.js and you can access your generated files on http://localhost:3000.

Sending whole folder content to client with express

I made an html5 game (using GameMaker), which is constituted of an index.html and a folder "html5game" that contains the dependencies of the game - the javascript code and the resources. The problem is the resources are quite numerous and diverse (sounds, sprites, etc.) and The client needs them all to play.
I am looking for a way to send them all without naming them specifically.
I tried the glob module :
var glob = require( 'glob' );
var files = glob.sync( './html5game/**' ).forEach( function( file ) {
require( path.resolve( file ) );
});
but I can't figure a way to send the files using res.sendFile() once I did that.
I tried
var express = require('express');
var app = express();
[...]
app.get('/aeronavale/jeu', function(req, res){
res.sendFile(__dirname + '/aeronavale/index.html');
res.sendFile(files)
});
[...]
app.listen(3000, function(){
console.log('app started on port 3000, yeah !')
})
but it gives me the error :
TypeError: path argument is required to res.sendFile
If you have an other solution, I a also interested. Thanks for your answers !
You will not be able to send multiple file like that with res.sendFile. The most straightforward thing that you can do here would be this:
Put your index.html file and your html5game directory into some common directory, e.g. called html and put it where you have your Node.js program. An example directory layout would be:
/home/you/yourapp:
- app.js (your node program)
- package.json (your package.json etc)
- html (a new directory)
- index.html (your main html to serve)
- html5game (the directory with other files)
- (other files)
Now, in your Node program you can use something like this:
var path = require('path');
var express = require('express');
var app = express();
var htmlPath = path.join(__dirname, 'html');
app.use(express.static(htmlPath));
var server = app.listen(3000, function () {
var host = 'localhost';
var port = server.address().port;
console.log('listening on http://'+host+':'+port+'/');
});
This will serve all of your files (including index.html) on addresses like:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
Of course you still need to make sure that you refer to your assets in your index.html file correctly, for example with:
<script src="/html5game/xxx.js"></script>
in the case of the example layout above.
The top level directory with your static assets (where you have your index.html) is usually called static, public or html but you can call it whatever you like, as long as you use the correct path in your call to express.static().
If you want to have your game available in some path other than the root path then you can specify it to app.use. For example if you change this:
app.use(express.static(htmlPath));
to this:
app.use('/game', express.static(htmlPath));
Then instead of those URLs:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
those URLs will be available instead:
http://localhost:3000/game/ (your index.html)
http://localhost:3000/game/html5game/xxx.js (your assets)
A lot of questions here are related to serving static files with Express so I made a working example and posted it on GitHub so that people could have a working starting point and go from there:
https://github.com/rsp/node-express-static-example
See also some other answers where I talk about it in more detail:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
onload js call not working with node
Loading partials fails on the server JS
Node JS not serving the static image
The workaround for this is to compress the directory using the archiver library and uncompress it on the front end.

Referencing java script files from html in nodejs server

I am having a node js server that serves index.html when user hits localhost:3000/
app.get('/', function (req, res){
res.render('index.html');
});
However i cant figure out how i can refer to myscript.js javascript file from within the index.html.
<script src="script/my_script.js" type="text/javascript"></script>
I am calling a click button function from this file, but at run time this call gives 404. Please let me know how i can refer to a javascript file from within index.html in a nodejs server setup.
You can set up a static directory in which express will serve files as-is. For example:
app.use("/", express.static(__dirname + '/public'));
You can then create a "public" directory in your app root, and move your "script" folder inside. Any files (such as javascript, css) inside will be served directly to clients.
Docs

How can I make script files available to the client in a Node.js Express app?

I'm building a Node.js Express app. When my client Html file tries to get a .js file from the server (when running <script src="somefolder/script.js"></script>), it can't access it. What's the common way to make script files accessible to the client in an Express app?
From the Express API:
Serve static content for the app from the "public" directory in the application directory:
app.use(express.static(__dirname + '/public'));
For example above assume that you will have the following "./public" folder structure:
/public
/javascripts
/custom.js
/stylesheets
/style.css
...
In this case to get script, or whatever you want you will need to write the following url: http://path_to_the_site/javascripts/custom.js.
Note that you don't need to write "public" before "javascripts".

Serving files in heroku node js application

I am new to node. I have created and successfully tested the node app in Heroku. My folder structure is something like this .
app.js ( the server side socket.iofile).
index.html (publicly available file).
when i access the app through the URL from Heroku.
If i access the app.js file like appname.herokuapp.com/app.js i can access the file. Is any way to prevent accessing this server file ?
Regards
Harilal
Well, probably you are using express.static() due to which it can access any static file from your directory.Anyways, you can create a route for app.js:
var app=express();
app.use(app.router); //this will make sure that node.js will check for a route before checking for app.js file and displaying it.
app.use(express.static(__dirname+'/directoryPath'));
//now set the route for app.js
app.get('/app.js',function(req,res){
//what-ever you want should happen when u go to appname.herokuapp.com/app.js
});
Actually am not using the "express".
My code is something like this
http://pastebin.com/7BcZZsMk
My folder structure is like the following:
app
----css
--------style.css
----images
--------cup.png
--------tree.png
----app.js
----index.html

Categories