2016-09-14 54 views
0

这是我的代码:

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'); 
}); 

这是我的输出,当我运行文件($节点test.js): 我想这是我的Ubuntu的机器上,它完美的作品。这是我在我的Mac上得到的。有人能解释我为什么会发生这种情况。任何帮助,将不胜感激。

 
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) 

回答

2

Http响应状态应该是整数。它不能是字符串,对象,数组或类似的,应该从100

开始从你的代码,我看到你尝试做

res.sendStatus(reply);

检查答复变量。从redis incr回应我认为它是字符串“OK”。

这是坏的。所以要修复它只是使用

res.sendStatus(reply ? 200 : 500);

而且检查。

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

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

编辑

如果您需要发送一些JSON或数据到前端只是做这样

res.json({thisIsMyNumber: reply});

res.send({thisIsMyNumber: reply});

希望这有助于。

+0

值为'2',从错误消息中可以看出。这是有道理的,因为它们从初始值1递增。 – mscdex

+0

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes stars from 100..Just change reply to 200 ... or 400 or whatever..But not小于100 –

+0

其实我正在实施一个非常简单的访客计数器。在这里,我试图计算由URI聚合的最近5分钟内的访问次数。我已经尝试了相同的代码在Ubuntu上,我得到正确的输出。即 3 ...最近五分钟内的访问次数。 但在我的Mac上,我得到这个错误。 如果这不是正确的方法,我该如何在我的页面上显示此号码?我很抱歉,这是我第一次与节点。 – ASP

相关问题