I need to initialize nowjs on this express server with vhosts.. How do I do that?
var host_api = express()
.get('/', function(req, res){
});
var host_secure = express()
.get('/', function(req, res){
});
express()
.use(vhost('api.domain.com', host_api))
.use(vhost('secure.domain.com', host_secure))
.listen(3000);
Initialize nowjs on simple http
var http = require('http'),
nowjs = require('now');
httpServer = http.createServer(function (req, res) {
res.send('Hello World\n');
});
httpServer.listen(3000);
var everyone = nowjs.initialize(httpServer);
Connect (on which Express is built) includes the required code to run vhosts.
You can see the documentation here: http://www.senchalabs.org/connect/vhost.html
For example:
connect() // Or "app" if app is an express application (see example below)
.use(connect.vhost('foo.com', fooApp))
.use(connect.vhost('bar.com', barApp))
.use(connect.vhost('*.com', mainApp))
Each "app" (fooApp, barApp, mainApp) is either a Node.js HTTP server or a Connect/Express app. You can create each app into a separate js file, and then include it:
var fooApp = require('foo/app.js').app
An example can be seen here: http://www.jondev.net/articles/vHosts_with_Node.JS_and_Express
Related
Why we pass "app" in http.createServer(app) as we can also pass
e.g :
var app = require('./app')
const http = require('http')
const port = 3500 || process.env.PORT
var server = http.createServer(app) //here we pass app
in other code we pass some different argument such as this
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port)
In your first example, I'm assuming that app represents an Express instance from something like this:
const app = express();
If so, then app is a request handler function that also has properties. You can pass it like this:
var server = http.createServer(app);
because that app function is specifically designed to be an http request listener which is passed the arguments (req, res) from an incoming http request as you can see here in the doc.
Or, in Express, you can also do:
const server = app.listen(80);
In that case, it will do the http.createServer(app) for you and then also call server.listen(port) and return the new server instance.
When you do this:
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port);
you are just making your own function that's built to handle an incoming http request instead of using the one that the Express library makes for you.
Quoting the Express documentation:
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):
var express = require('express')
var https = require('https')
var http = require('http')
var app = express()
http.createServer(app).listen(80)
https.createServer(options, app).listen(443)
https://expressjs.com/en/api.html
I am trying to follow this tutorial on creating a simple chat application using socket.io. I am at the part of the tutorial where I have to insert all of the code below into a js file and initiate it. I just don't understand why the 2nd of code exist, I heard that express can do a lot more than http. Instead of using the "http.listen" code, can't "app.listen" be used and "app" passed to "io" instead?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Why do I need to add “require(”http“)” when I already have express?
You don't have to manually load the http module yourself. You use express to create an http server for you (it will load the http module for you) and integrate it with socket.io without manually loading the htttp module like this:
const app = require('express')();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
const server = app.listen(3000, function(){
console.log('listening on *:3000');
});
const io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
});
Internally, app.listen() loads the http module for you, creates a server and then starts it, returning the server object which you can then use with socket.io.
Inside of express, this is the code for app.listen():
const http = require('http');
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, somebody had to load the http module. If you use app.listen(), the express will do it for you.
You are right. Express is a framework that sits on top of the nodejs application and provides a much easier,provided more middleware to handle routes, session and cookies and more efficient way to create server as such
var express = require('express');
var app = express();
app.listen(3000);
In this example, for the purpose of creating a socket between different channels, you have to use HTTP to indicate that the socket is used to handle HTTP requests/responses. You simply can't pass an entire express application to io.
I want to create a simple Node.js server to do the following :
With my application I just do the command http.get(Node.Js_Server_address/json) to get the json file data stored on my server.
Could please help me with a tutorial? Any help would be appreciated!
This is very simple example of node.js server:
var app = require('./app');
var http = require('http');
var server = http.createServer(app);
server.listen(8080, function() {
console.log("listening to: http://127.0.0.1:8080");
});
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
there is a nice tutorial here and here ...
you can use npm to install node.js and all the packages that you need for it.
hope it helps.
There are lots of examples on this topic, i think you should make some googling before next time.
You can create a REST server via express module of nodeJs. In your server folder use npm install express to download express module. You can get more information about express from here. After that create a server.js file in your server folder.In server.js
var express = require('express');
var app = express();
var PORT = 8080;
/* req stands for request, res stands for response */
app.get('/json',function(req,res){
res.json(yourData);
})
app.listen(PORT,function(){
console.log('Express is listening port:' + PORT + '!');
})
So this should do the work. Let me know if this helps you.
I'm developing a multi-player HTML5 game using Node.js for an Express server and Socket.io for websockets. When I try to access the game in my browser going to the port the application is listening to, I get a blank page. However, when I access the index.html file directly (while the server is running), it works perfectly.
Note, when I say "access the file directly" I mean: file:///C:/Program%20Files/nodejs/SupermarketChallenge/public/index.html
This was fine until I wanted to test the game with my housemate who needs to access it through localhost in order to play!
Here's the relevant server code:
var express = require('express'),
//Create an express server
app = express.createServer(),
//attach socket.io to the server
supermarket = require('socket.io').listen(app);
//Configure a static directory for public files
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
//set the port to listen to
app.listen(3000);
And the client:
var socket = io.connect('http://localhost:3000');
It's because going to http://localhost:3000/ does not match any valid files from your public folder. You need a route to match this. Update your code according:
var express = require('express'),
//Create an express server
app = express.createServer(),
//attach socket.io to the server
supermarket = require('socket.io').listen(app);
//Routes
app.get('/', function(req, res) {
res.redirect('/index.html');
});
//Configure a static directory for public files
app.configure(function() {
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
//set the port to listen to
app.listen(3000);
Now your route can be altered to actually serve the content of the index.html, in which case you would replace the / route with the following:
//Routes
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
const app = require("express")();
const httpServer = require("http").createServer(app);
const options = { /* ... */ };
const io = require("socket.io")(httpServer, options);
io.on("connection", socket => { /* ... */ });
httpServer.listen(3000);
// WARNING !!! app.listen(3000); will not work here, as it creates a new HTTP server
I have a very basic node script that starts up, serving up an html page and finally closes the app (kills the node process ideally). Everything works great except the last line that invokes the close method to tear it down.
var express = require('express')
, http = require('http')
, app = express()
, server = http.createServer(app);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(8090);
console.log("started...");
app.close();
The error I get when I run this w/ node 0.8+ is
app.close();
^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'close'
Anyone know how I can more safely close the express app down?
You were so close:
var express = require('express')
, http = require('http')
, app = express()
, server = http.createServer(app);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
var listener = app.listen(8090);
console.log("started...");
listener.close();
So far the best approach I've found it to kill the node process. seems to get the job done (although for purity I'd like to just close express)
process.exit(code=0)
process.on('SIGTERM', function () {
app.close();
});
Try that