Express server does not receive request, http module server does - node.js

I am making a HTTP server for a Biometric device. I cannot make changes to the devices firmware. I can just add the server ip.
So I first made an express server to receive requests, but it didnt receive any. Later I made a server using http module of Nodejs and voila it was able to do so.
The problem is writing a server for a very big application in http module would be difficult and there is very less support available for it. I'd prefer to user Express. Any Ideas why express is failing?
Edit:
So someone asked for code here they are:
http module
var http = require('http');
var port = 7005;
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log(request.method);
console.log(request.headers);
console.log(request.data);
response.write('hi');
response.end();
});
s.listen(port);
console.log('Browse to http://127.0.0.1:' + port);
Express Server:
var express = require('express')
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// respond with "hello world" when a GET request is made to the homepage
app.all('/', function (req, res) {
res.send('hello world')
console.log(req.method + " Request Aayi");
console.log(req.body);
});
app.listen(7005);

Related

Why we pass "app" in http.createServer(app)

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

Twilio 11200 HTTP retrieval failure with Node app on Heroku

My Node.js app is set to respond to a text message received at a paid Twilio number. I tested it using ngrok and everything worked fine. Once I deployed the app to Heroku, however, I started seeing an 11200 HTTP retrieval failure error in the Twilio console.
Are there configuration settings in Heroku that I need to set up?
// Twilio Credentials
const accountSid = 'xxx';
const authToken = 'xxx';
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;
var express = require('express');
var app = express();
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 3000));
app.use('/', function(request, response){
response.send();
});
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your
unique id # XXXX');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
app.listen(app.get('port'), function() {
// console.log('Node app is running on port', app.get('port'));
});
Twilio developer evangelist here.
I think the problem is mostly in the method you are using to send the response. Currently your final line of the /sms route is res.end(twiml.toString()); however Response#end is used "to quickly end the response without any data."
I think your use of res.writeHead() might be outdated now too.
I would change your /sms route to something like this:
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your unique id # XXXX');
res.set('Content-Type', 'text/xml');
res.status(200).send(twiml.toString());
});
Then try redeploying to Heroku and see what happens.

Express won't send headers

I've done this from scratch and it still gives me an error...
I've run
express test
then
cd test && npm install
I've edited the app.js adding a route such this:
app.get('/test',function(req,res) {
res.writeHead(200, {"Content-Type": "application/json"});
return res.send('{"a":3}');
});
Then I've run node
node app.js
And when I try to access http://server/test I get
Error: Can't set headers after they are sent.
I'm using
Node v4.2.1, Express 2.5.8, npm 3.4.0.
This just happens with Express, if I create a simple server on Node I can use writeHead.
When res.writeHead(200, {"Content-Type": "application/json"});,you send all the response headers to the client,so you can not send header again.
Because res.send is the function of express's response object,I look the source code of this send function:
chunk is what you send here : String('{"a":3}')
this.set('Content-Type', setCharset(type, 'utf-8')) here express helps us concat our content-type with utf-8 so server needs to send header again
That is why you get the error.
Ps.
Sorry for my bad english and I hope you understand what I try to explain.
What about using res.setHeader
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.setHeader("Content-Type","application/json");
res.send('{}');
});
var server = app.listen(3000, function () {
var host = "localhost";
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

How to initialize nowjs on express with virtual hosts

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

nodejs hangs with express static files

The Problem:
If I comment out the express['static'] line, the code runs perfectly. If I include it (or change the order), the app hangs for a while before responding.
To Recreate:
Run the app, load up a browser and go to 127.0.0.1:51783
Refresh the page constantly (or use curl), the console will give you an output similar to:
GET / 1 ms
Then, when the timeout kicks in and the 15 requests are sent, the server becomes unresponsive and you get the following:
Server Now Unresponsive but requests queued
GET / 35549 ms
app.js
var http = require('http');
var express = require('express');
var app = express.createServer();
app.use(express.logger({ format: '\x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :response-time ms' }));
app.use(express.bodyParser());
app.use(express['static'](__dirname + '/')); //Comment me and all works perfectly!
app.listen(51783);
http.globalAgent.maxSockets = 500; //doesn't help
setTimeout(function(){
console.log('Server Now Unresponsive but requests queued');
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].forEach(function(item){
http.request({host:'http://cnn.com', port:80, path:'/null', method:'GET'}, function(res){
}).on('error', function(e){});
});
},5000);
There is something not quite right about that http request. I recommend using the request module for this sort of thing. Either way this works:
var http = require('http');
var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.logger({ format: '\x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :response-time ms' }));
app.use(express.bodyParser());
app.use(express['static'](__dirname + '/public')); //Comment me and all works perfectly!
})
app.listen(51783);
var request = require('request');
setTimeout(function(){
console.log('Server Now Unresponsive but requests queued');
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].forEach(function(item){
request('http://www.google.com', function (error, response, body) {
console.log("request number "+item+" received")
})
});
},5000);

Resources