ASP ASP - 2 months ago 181
HTTP Question

_http_server.js:192 throw new RangeError(`Invalid status code: ${statusCode}`);

This is my code:

var express = require('express');
var http = require('http');
var redis = require('redis');
var url = require('url');
var client = redis.createClient().setMaxListeners(0);

var app = express();
app.set('port', 3000);

app.get('/*', function(req, res) {
var key = url.parse(req.url).pathname;
client.on('connect', function() {
console.log('connected to redis!');
});
client.get(key, function(err, reply) {
if( reply == null) {
client.set(key, 1);
client.expire(key, 300);
res.send('1');
}
else {
client.incr(key, function(err, reply) {
console.log('increment value: ' + reply);
res.sendStatus(reply);
});
}
});

});


http.createServer(app).listen(app.get('port'), function() {
console.log('listening');
});


This is my output when I run the file ($ node test.js):
I tried this on my ubuntu machine and it perfectly works. This is what I get on my mac. Could someone explain me why this is happening. Any help would be appreciated.


listening
increment value: 2
_http_server.js:192
throw new RangeError(`Invalid status code: ${statusCode}`);
^

RangeError: Invalid status code: 2
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:559:10)
at ServerResponse.send (/Users/sharath/webapps/docker/node_modules/express/lib/response.js:209:10)
at ServerResponse.sendStatus (/Users/sharath/webapps/docker/node_modules/express/lib/response.js:346:15)
at Command.callback (/Users/sharath/webapps/docker/test.js:24:13)
at normal_reply (/Users/sharath/webapps/docker/node_modules/redis/index.js:714:21)
at RedisClient.return_reply (/Users/sharath/webapps/docker/node_modules/redis/index.js:816:9)
at JavascriptRedisParser.returnReply (/Users/sharath/webapps/docker/node_modules/redis/index.js:188:18)
at JavascriptRedisParser.execute (/Users/sharath/webapps/docker/node_modules/redis-parser/lib/parser.js:415:12)

Answer

Http response statuses should be integers. It cannot be strings, objects, array or like that and should begin from 100.

From your code i see that you try to do

res.sendStatus(reply);

Check reply variable. From redis incr response im thinking it's string "OK".

Which is bad.. So to fix it just use

res.sendStatus(reply ? 200 : 500);

Also check this.

http://expressjs.com/en/4x/api.html#res.sendStatus

And this

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

EDIT

If you need to send some JSON or data into front-end just do like this

res.json({thisIsMyNumber: reply});

or

res.send({thisIsMyNumber: reply});

Hope this helps.