Running website on node js server - javascript

I want to access my node app from my base url path, example.com so I set my listening port to 80 inside my app.js file with express js.
Below is my app.js file. Credit: node static site tutorial.
var express = require('express');
var path = require('path');
var app = express();
// Define the port to run on
app.set('port', 80);
app.use(express.static(path.join(__dirname, 'public')));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
I start my server with node app.js and can access my content as intended - but as soon as my connection is closed, my site is inaccessible. This is my first time experimenting with a non LAMP solution.
How can I keep my node server running on the cloud to serve my website? Is this what we call "deploying node to production?".
This is just a personal site with some static html / js files.

When you close the connection, you close the shell session you started node in.
Since you are running it in linux, simplest method is to run it in background node app.js &
Or you can install screen for a terminal which will stay running & can be detached from your current session. http://www.thegeekstuff.com/2010/07/screen-command-examples/
Also, In case of unhandled errors in your code, servers programs can crash. To keep the server running & restarting when crashed use nodemon or forever.

Related

Run Node.js on a Google Compute Engine Debian server

I have a debian server running on Google Compute Engine with a host like example.com and I'm trying to run a node.js app on a directory like example.com/mynodeapp.
Node.js, NPM are installed properly on the debian server.
I'm running pm2 start main.js from the root of example.com/mynodeapp and everything running but when I go to example.com/mynodeapp, I have nothing, just the indexing of the files.
Express.js configure
main.js (entry)
var express = require('express')
var vhost = require('vhost')
express()
.use(vhost('example.com/mynodeapp', require('./dist/index').app))
.listen(8080)
dist/index.js
var express = require('express')
var app = express()
app.get('/', function(req, res) {
res.send('Hello World!');
})
exports.app = app
With .listen(8080) the port is set to 8080, so you'll have to change that or try example.com:8080.
Note that you will run into one of two problems, depending on your choice: Port 8080 is probably not open – you'd have to allow it in the firewall.
If you're currently getting a file listing on port 80, there's some other server running (possibly apache or nginx from the standard debian install). You will have to stop that server to free up the port.

Reflected client actions from a different computer

I'm working on my new blog, for now the server side is NodeJS(using expressjs), I host the server on my computer.
For rapid development I'm using GulpJS.
Before I explain the weird thing. Let me say that both ports(3000 and 80 are open).
Gulp version: 3.9.0
NodeJS version: 0.10.35
Browser-sync: 2.7.12
This is my index.js, I use node index.js to start the server.
var express = require('express');
var app = express();
app.use(express.static('public'));
app.set('base', '/public');
app.get('/', function(req, res) {
res.sendfile('index.html');
});
var server = app.listen(80, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app istening at http://%s:%s', host, port);
});
Now this is the important part from gulpfile.js I use(I removed most tasks for simplicity):
var sync = require("browser-sync").create();
gulp.task('browser-sync', function() {
sync.init({
proxy: "http://localhost:80",
browser: "chrome",
port: 3000
});
});
So after I work a while on the my blog I decided to show it to a friend, while the NodeJS server is running and Gulp is watching over some html, js and sass files, I send my domain.ml:3000 to my friend, the domain points to my external IP and the port 3000 is due to the proxy defined via the gulpfile.js.
The weird thing I can't explain:
While my friend played with the website his actions were reflected to me, meaning we both visited domain.ml:3000 and when he clicked a link with src attribute set to #, on my side the url changed to domain.ml:3000/#, I also have a link that when clicked opens a tab(the transition is made by some js+css transitions) and again when the tab opens on his side it also opens on my side.
I'm thinking it's something with the browser-sync proxy but I can't explain nor understand this behavior, if anyone can help me figure it I'll be very thankful, have a nice day.
That's basically what browser-sync is meant to do. You can sync browsers to test the same app simultaneously. That will change once you make a gulp build and serve that build, instead of your 'dev version'.
This is the deal, browser-sync is sending the hash url via your proxy to your server (as you click links with '#') that fragment has a somewhat different treatment.
The server on port 80 is now a puppet replaying all URLS from your browser-sync session, you are both connected on browser-sync port 3000, when one of you sends in a hash change, you both receive the new location as you server on port:80 now also has the new location.

Express and node.js run from a folder; all links point to url root

I have installed node inside a folder and am forwarding it through apache. I am doing this because I have several virtualhosts run through apache, and I do not want to take the time to set up everything through node.
Apache and Node.js on the Same Server
However, I am trying to create a chat engine. I try to include some js files, but they search for http://example.org/myscript.js instead of http://example.org/chat/myscript.js
I got around this by using
<base href="/chat/">
However, now I am trying to integrate socket.io. I included socket.io from https://cdn.socket.io/socket.io-1.3.5.js because I could not get the locally serverd /socket.io/socket.io.js to properly be located.
Now socket.io is trying to connect to http://example.org/socket.io
That dierectory does not exist. If anything, the proper path should be http://example.org/chat/socket.io
I have been looking all over the internet for a solution. There must be something fundamental or obvious about how nodejs/express operates that I am missing. Thanks a million!
Server.js - This is the file I start with node.
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http, { log: true, resource:'/socket.io/'});
app.use('/socket.io', express.static(path.join(__dirname,'/node_modules/socket.io/lib/')));
app.use('/bootstrap', express.static(path.join(__dirname,'/node_modules/bootstrap/dist/')));
app.use('/', express.static(__dirname));
var server = app.listen(8000);
io.sockets.on('connection', function(socket) {
console.log('A user connected!');
})

Getting an express app working online

I am new to expressjs and am trying to get my express application (done with the express generator) working on my website, I currently uploaded the directory which is is contained in like so..
http://www.example.com/express-app-here
so I could see it working online. However, when I navigate to where the App is, I seem to only get the directory structure, and express isn't routing me to the appropriate place like it is when I go to localhost:3000.
I take it this has something to do with the fact that express isn't executing my application? Locally,
npm start
needs to be run on the console in order to get it to run, is there some kind of log I need to execute this command in? Or something I need to change in the app.js or /bin directory?
As it was said in the comments, you need to have nodejs installed on your server. It's not as simple as just copying the node app directory over to the server.
You will have to install node and npm on the server, and then run your app from the server, probably using npm start like you were doing on your local machine.
From there, you will want to go into your app code and make sure a route exists for /express-app-here unless you want www.example.com:3000 to take you directly to the express app.
Basically do it like this:`
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var port = process.env.PORT || config.webServer.port || 3000;
server.listen(port, function () {
console.log('server running');
console.log(port);
console.log(server);
});
exports.module = exports = app;
save it app.js
Go to path via cmd. Now run:-
1)npm install express
2)npm install http
3)node app.js
Will be enough to run express server

Node.js socket.io.js not found or io not defined

I'm trying to run a node.js application on my freebsd server, but I can't get the socket.io library to work with it. I've tried including:
<script src="/socket.io/socket.io.js"></script>
Which gives a 404 error, and if i link directly to the file (i.e. where it is in my public_html folder) I get the io not defined error.
Thanks in advance
Try creating another node.js application that has this single line in it and then run it with node.js
var io = require('socket.io').listen(8000);
Then in your browser visit http://127.0.0.1:8000 and you should get the friendly "Welcome to socket.io." greeting. If you are getting this then socket.io is running and will serve the socket.io.js file.
The only other thing that I can think of that might be happening is that you might not be linking to the alternate port in your client file. Unless you're running the socket.io server on express which is running on port 80. For now create a client file that has the script source for socket.io set to
<script src="http://127.0.0.1:8000/socket.io/socket.io.js"> </script>
This should connect to the socket.io server running on port 8000 and get the socket.io.js file.
Your node.js application still has to serve it - it does not get served automagically. What do you have in your server? It should be something like
var app = require('express').createServer();
var io = require('socket.io').listen(app);
or similar (the listen is important). The location is not a real location on the disk - socket.io library should intercept the URL and serve its clientside library, as far as I understand.
Add the following after body parser:
, express.static(__dirname + "/public")
So something like:
var app = module.exports = express.createServer(
express.bodyParser()
, express.static(__dirname + "/public")
);
For those who got the same kind of issue if they run (open) your html file directly from your local file directory(ex: file:///C:/Users/index.html).
Solution: You have to run(open) the file through localhost (ex: http://localhost:3000/index.html) where the server is listening to.
Below code snippet shows how to create a server and how to wire together with the express and socket.io
const express = require("express");
const app = express();
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
///////////////////////////////////////////////////////////////
// Any other server-side code goes here //
//////////////////////////////////////////////////////////////
httpServer.listen(3000, () => {
console.log(`Server listening to port 3000`);
});

Categories