Getting an express app working online - javascript

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

Related

Correct NodeJS server for Vue.js application

I'm using Vue.js and the vue-router and would like to server the static files via Node.JS.
So I've create server.js with the following code:
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
It seems to work, but only when I click around.
If I visit ex. my-url.com/some-path/another-path it fails.
Am I missing something?
Ex. I'm getting:
Cannot GET /cars with I type www.my-domain.com/cars into the address bar in the browser, but visiting www.my-domain.com and clicking on cars does work.
You need to setup your server to redirect users to the appropriate server location. Please read the Vue Router - HTML5 History Mode docs.
When using history mode, the URL will look "normal," e.g.
http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client
side app, without a proper server configuration, the users will get a
404 error if they access http://oursite.com/user/id directly in
their browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple
catch-all fallback route to your server. If the URL doesn't match any
static assets, it should serve the same index.html page that your
app lives in. Beautiful, again!
The main thing that you need to do is have all routes lead to the root route. Alternatively, since you are using Express, you can leverage the connect-history-api-fallback which the Vue Router docs recommend.

How to combine socket.io with some of the simple static http servers on Node.js?

I have created a Socket.IO application and I even already got some interactivity working. But I still host static content on Apache HTTP server (localhost, XAMPP bundle). Actually when running Node.js, this is my working directory:
C:\xampp\htdocs\game>node nodeGame.js
I'd like to move it all somewhere else, probably convert it into npm package and use Node.js to serve HTML and JavaScript files to user. It would be best if I could just install some simple handler that could be passed into http. Something like:
var http = Http.Server(require("really-simple-http-server"));
var io = SocketIo(http);
// Sockets below
None of the servers I found on StackOverflow seemed that simple, so which is most suitable for this purpose and how to use it?
You can use socket.io with the Express framework (using Express as your web server) and then use express.static() to serve static files:
var express = require('express');
var app = express();
var server = app.listen(3000, function() {
console.log("server started on port 3000");
});
var io = require('socket.io').listen(server);
// set up static file serving from the public directory
app.use('/static', express.static(__dirname + '/public'));
Details on the options for serving static files with Express are here.

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

node.js /socket.io/socket.io.js not found

i keep on getting the error
/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined
my code is
var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
and
<script src="/socket.io/socket.io.js"></script>
what is the problem ???
any help is welcome!
Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.
If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.
Code sample Express 3.x -
Express 3 requires that you instantiate a http.Server to attach socket.io to first
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
//...
server.listen(8000);
Happy Coding :)
How to find socket.io.js for client side
install socket.io
npm install socket.io
find socket.io client
find ./ | grep client | grep socket.io.js
result:
./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
copy socket.io.js to your resources:
cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/
in your html:
<script type="text/javascript" src="resources/js/socket.io.js"></script>
It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).
Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.
Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.
... "You might be wondering where the /socket.io/socket.io.js file
comes from, since we neither add it and nor does it exist on the filesystem. This is
part of the magic done by io.listen on the server. It creates a handler on the server
to serve the socket.io.js script file."
from the book Socket.IO Real-time Web
Application Development, page 56
You must just follow https://socket.io/get-started/chat/ and all will work.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
console.log('listening on *:3000');
});
If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.
app.use(express.static(path.join(__dirname, '/')))
This is because in the tutorial, Express will only catch the url
/ and send the file of index.html.
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).
Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');
make sure you index.html in proper directory
Steps to debug
npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.
Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>
const socket = io.connect("localhost:5000");
$(() =>
Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data
Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)
const cors = require("cors");
const http = require("http").Server(app);
const io = require("socket.io")(http);
Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file
app.use(cors());
app.use(express.static(__dirname));
As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.
const server = http.listen(5000, () => {
console.log("your-app listening on port", server.address().port);
});
As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.
I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.
If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io
like
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>
while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.
If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.
Illustration(FileName: index.js):
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//MiddleWares
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('index.html');
});
io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
console.log(`App has been started at port ${port}`);
});
After this run your server file by the command
node index.js
Then open the localhost:${port}, Replace port with given in the index.js file and run it.
It solved my problem. Hope it solves yours too.

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