I've read many posts on Nodejs and Expressjs for that matter but I still don't understand how this works:
This is the basic Hello World application with Express.js (taken from http://expressjs.com/starter/hello-world.html).
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
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)
})
How are we able to get host and port using server when we are still in the process of getting what we'll eventually bind to the var server?
Because it's asynchronous. The callback is only being run later, after server is defined and initialized.
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)
})
Proper indenting sometimes helps see this.
Related
I'm learning Js.
I have a problem in the code:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, function(){
console.log("The Express is running");
});
app.get('/', (req,res)=>{
res.send('Ok');
});
running node app.js i have the answer "Ok".But, running in the browser(localhost:3000) i get : "The connection was refused".
necessary info: I'm use a container docker, which I use the ubuntu. Can this cause a problem?
When I start up a basic express.js server I usually console.log a message that says it is running and listening on port .
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('App reached.'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
However, I would like to add to this message the available IP address exposing the app to other machines on the network. Somewhat like create-react-app basic template does. How can i reach that info with my javascript code?
Has indeed already been answered:
Get local IP address in node.js
I preferred this solution:
npm install ip
const express = require('express');
const ip = require('ip');
const ipAddress = ip.address();
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('App reached.'));
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`);
console.log(`Network access via: ${ipAddress}:${port}!`);
});
I am trying to follow tutorial on how to use socket.io with express.js framework and node.js.
Every tutorial I am following suggested I use the following lines to establish a connection in app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(3000);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
})
This worked if I use port other than 3000 which I am having to run my application on http://localhost:3000/. I get the error that Port 3000 already in use.
After debugging and looking at the code I think I have an idea of why is this happening. In ./bin/www.js file (created automatically by express js) we have the following lines:
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
but I am not sure how to reuse this created server with same port in my app.js. I am totally new to node.js. How do I setup socket io on the express framework the right way?
hello there please put your server.listen after socket connection like this
var app=require('expess')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
})
server.listen(3000);
I hope this would work.Thanks
In order to kill any existing node process, you can run killall node command in your shell.
Remove this line from your code, which is hardcoding the port number -
server.listen(3000);
and add something like this instead -
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'));
So your code would look something like -
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// server.listen(3000);
app.set('port', process.env.PORT || 3000);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
server.listen(app.get('port'));
Now when your run your app again, it would boot on port 3000 by default or you can pass an environment variable (PORT) while starting the server like this to run on other ports.
$ PORT=8080 node app.js
I referred to the previously asked question on this but couldnt resolve it. I have Express server installed and trying to run Index.html file through it.
But I am getting 'Cannot GET /' as the response.
Here is the server.js through which I calling the index.html
var express = require('express');
var app = express();
app.get('index.html', function (req, res) {
app.use("/", express.static(__dirname));
});
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);
});
Thanks in advance!!
When you access a directory on your hosted site, say the root directory of localhost on port 8080, using http://localhost:8080/ for URL, the browser does not send a request for 'index.html` to the server and just uses whatever the server sends back.
It's the express static middleware which in response to a browser request with no filename will check if the folder exists and (by default) return any index.html contained in the folder. So your line of code for routing, app.get('index.html') never executes, and the browser gives you the error message.
Here's a mini static express server if you want to try it.
var express = require('express');
var app = express();
app.use(express.static('../public')); // path to your public directory
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
If you want a simple static, folder-as-server kind of thing, you can do it without express way like "/public":
var fs = require("fs");
var host = "localhost";
var port = 8000;
var express = require("express");
var app = express();
app.use('/', express.static(__dirname));
app.listen(port, host);
I put this in the file express.js, so that is in the same folder than index.html (even associated .js with node.exe). This way the folder is the root of the server.
I tried to connect python client to node.js server, and experience HTTP 400 errors.
node.js server code:
var socket = require('socket.io');
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 8080);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = socket.listen(server);
io.sockets.on('connection', function () {
console.log('hello world im a socket');
});
python client code:
from socketIO_client import SocketIO
def on_response(*args):
print 'on_response', args
import logging;
logging.basicConfig(level=logging.DEBUG)
socketIO = SocketIO('localhost', 8080)
socketIO.on('news', on_response)
socketIO.wait(seconds=1)
when i run client.py after starting the server getting the following error:
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): localhost
DEBUG:requests.packages.urllib3.connectionpool:"GET /socket.io/1/ HTTP/1.1" 400 None
If I create a javascript client, then it works well. Could someone help me resolve this issue please?