.on('connection') for an express server - node.js

I am trying to create a basic web server with express for node.js. I know that the http module has a .on('connection',function(client){}) method that is called whenever a client connects. Is there a similar method for express?

I know this question is quite old, but I had the same one and was able to figure out the answer, so I thought I would post it here for anyone else who may be looking.
According to the Express docs with Express 4.x, the listen method returns an http.Server object, so all methods that can be used on http.Server.listen are also available on the Express listen method.
With this in mind, the answer to your question is yes, and below is an example of how you can achieve it in Express 4.x.
const app = express();
app.use('/', function (req, res, next) {
// Add your code for this route here
});
const server = app.listen(3000, function () {
console.log('Server listening on port 3000');
});
server.on('connection', function (client) {
// Do your thang here
});

You can easily add a route that will be matched against "everything", that is:
app.use('/', function (req, res, next) {
console.log("received request: " + req.originalUrl);
next();
});
This is simply a middleware that, once a client executes any rest api to your server, will log the url and call next() to continue to the next matching route

Related

Can I pass multiple functions to an http.createServer in NodeJS?

I'm completely new to server development and NodeJS, so my apologies if this question sounds stupid or if such a question already exists.
I was following a simple NodeJS tutorial and building a simple "Hello World" server. I noticed that http.createServer took only one function as its argument.
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end("Hello World");
}.listen(8080);
I tried passing another function to it like the following:
var http = require('http');
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type':'text/html'});
res.end("Hello World");
},
function (req, res) {
res.write("Blahblah");
res.end();
}
).listen(8080);
But hitting localhost:8080 returned only Hello World.
So I was wondering if I could pass multiple functions to it and if not, then why.
Thank you for your time
You cannot pass multiple functions. If you want multiple listeners for incoming requests, you can just register another listener for incoming requests:
const server = http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end("Hello World");
}.listen(8080);
// add additional listener
server.on('request', function(req, res) {
if (req.url === "/goodbye") {
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.end("goodbye");
}
});
Note: right from the doc for http.createServer(), it says this about the function parameter passed to http.createServer():
http.createServer([options][, requestListener])
The requestListener is a function which is automatically added to the 'request' event.
Doc for the request event is here.
As others have said, it is pretty rare to use a plain http server like this because some simple routing is nearly always helpful and a lightweight framework like Express offers very useful features without really getting in the way of anything you might want to do. In the case of Express, you'd use code like this:
const express = require('express');
const app = express();
// define handler for /goodbye URL
app.get('/goodbye', function(req, res) {
res.send("goodbye");
});
// define handler for /hello URL
app.get("/hello", function(req, res) {
res.send("hello");
});
const server = app.listen(8080);
Here express, keeps a list of the URLs that you wish to handle and then listens for each incoming request, compares it against the URLs you wanted to handle and calls the appropriate route handler. It has lots of other features for routing too such as middleware, wildcards, parameterized URLs, etc...
I'd recommend you use something like express if you want multiple routes:
const express = require('express');
const app = express();
app.get('/hello', (req, res) => res.send('Hello World!'));
app.get('/world', (req, res) => res.send('Hello World!'));
app.listen(3000, () => console.log('Example app listening on port 3000!'));
Node.js provides you with the features to create your own webserver from scratch, unless you want to create a whole new framework i would recommend using something like expressjs.
Have a look at this following tutorial if you're a newbie and want to create restful services.
Build a RESTful API Using Node and Express 4 | Scotch.io
Its a fairly simple and straightforward tutorial

Node Express: does order of calls matter?

Node Express documentation gives a hello-world example:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Does the order of listen() and get() matter? (could they be swapped?) And what would happen if get() and listen() were called a second time after the first calls as above?
Let's deconstruct the example :
app.listen(3000)
this line attaches your app to a port, in this case 3000. It enables you to access it by typing http://localhost:3000, you typically would not want to change the port you app runs on durig execution.
app.get('/', function (req, res) {
res.send('Hello World!')
})
this is basically a listener, which will be called when you make a GET request to the / route. It tells your app what to answer when you type the url on your browser.
It is attached to the app object, whether the app is running or not, so it can be written before listen, after, or in another file altogether.
In the strange case where you'd have a second listener on the same route, one of them would not be executed. I suggest you test it yourself if you really want to know which takes precedence, here's a sample code :
app.get('/', function (req, res) {
res.send('Will I be executed?')
});
app.get('/', function (req, res) {
res.send('or maybe I will?')
});
app.listen(3000)

Capture all http requests with node/express

I am looking to capture all of the data from any request (images, fonts, css, js, etc) on my website so that I can capture the file details, specifically the file name and file size. I have found almost an identical question/solution:
Node.js : How to do something on all HTTP requests in Express?
But the solution appears to be deprecated with Express v4. Is there a simple solution to do this? As another approach I have tried the below solution with no luck:
var express = require("express");
var path = require("path");
var port = process.env.PORT || 3000;
var app = express();
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.get("/", function(req, res){
// I want to listen to all requests coming from index.html
res.send("index.html");
});
app.all("*", function(){
// can't get requests
})
app.listen(port, function(){
console.log(`server listening on port ${port}`);
});
Also I am not looking to do this from Fiddler/Charles because I am looking to display this data on my site.
Express routes are predicated on order. Notice the answer that you linked in your question has the middleware defined, and used before all other routes.
Secondly you're trying to implement something that requires middleware, not a wildcard route. The pattern in link you provided in your question is not deprecated according to their docs.
app.use(function (req, res, next) {
// do something with the request
req.foo = 'testing'
next(); // MUST call this or the routes will not be hit
});
app.get('/', function(req, res){
if (req.foo === 'testing') {
console.log('works');
}
res.send("index.html");
});

How can I use middleware alongside express.static?

I have a nodejs application that serves a single page app via express.static. This all works fine, however when I try and create a simple piece of middleware:
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
});
app.use(express.static(path.join(__dirname, 'client')));
any attempt to load content from client fails with:
TypeError: Object function (req, res, next){
console.log('%s %s', req.method, req.url);
next();
} has no method 'concat'
If I use the middleware after the express.static call it works fine - but isn't called for static content. I need to setup the middleware so that any flash messages (from connect flash) can be sent as cookies to the static content.
Does anyone know how I can use middleware for all content, including static content? Eventually I'll be serving two folders, one public and one private (authenticated via passport).
I've put together a minimal implementation of your question and it works for me:
var express = require('express')
var path = require('path')
var app = express()
app.use(function(req, res, next) {
console.log('Middleware says %s %s', req.method, req.url);
next();
})
app.use(express.static(path.join(__dirname, 'client')))
app.listen(8080, function() {
console.log('server is ready')
})
I then started the server
$ node so.js
server is ready
and loaded http://localhost:8080/foo.txt in my browser
Middleware says GET /foo.txt
I'm using Express 3.6.0 - if you're using an older version of Express then you may well have stumbled across a bug that's since been fixed, similar to this one. If updating doesn't solve your problem then I would recommend updating your question to contain more code, perhaps a runnable, yet minimal example of the issue. Hope this helps!

What all can app.get in express be used for?

It can be used for
app.get('/', function(req, res){
res.send('hello world');
});
which is to display in browser upon receiving request on Port defined.
What other uses are there of the command app.get?
app.get has two uses.
the first is using it as a route just like you showed,
or even using multiple middlewares additionally to the route like in the following example:
var middleware = function(req, res, next) {
//do something, then call the next() middleware.
next();
}
app.get('/', middleware, function (req, res) {
res.render('template');
});
but app.get can also be used together with app.set:
var appEnv = app.get('env'); //tells you the environment, development or production
var appPort = app.get('port'); //tells you the port the app runs on
console.log('app is running in ' + appEnv + ' environment and on port: ' + appPort);
app.set('any-string', 'any value'); //set custom app level value
var any_string = app.get('any-string'); //retrieve custom app level value
console.log('any_string = ' + any_string);
thats the uses for app.get i found so far,
have fun
jascha
In express app.get or app.post is used to define a route. Both of them work the same way. They accept two parameters
1) A string that defines the path of the route
2) A single or multiple callbacks.
app.get('/', function(req, res){
res.send('hello world');
});
What the above code does is it tells express that when a request is made on / endpoint it executes the code in the callback function. The function that you have defined just sends an html message
However there are lot's of different responses that you can send to the browser. They are enumerated in the guide

Resources