这是我的代码:
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');
});
这是我运行文件($ node 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)
最佳答案
Http 响应状态应该是整数。它不能是字符串、对象、数组等,并且应该从 100 开始。
从你的代码中我看到你尝试这样做
res.sendStatus(reply);
检查回复变量。从redis incr响应我认为它是字符串“OK”。
这很糟糕..所以要修复它只需使用
res.sendStatus(回复?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});
希望这有帮助。
关于node.js - _http_server.js :192 throw new RangeError (`Invalid status code: ${statusCode}` );,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39500832/