gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:09:45 25 4
gpt4 key购买 nike

这是我的代码:

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 上得到的。有人可以向我解释为什么会这样。任何帮助将不胜感激。

listeningincrement 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(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});

希望这对您有所帮助。

关于node.js - _http_server.js :192 throw new RangeError (`Invalid status code: ${statusCode}` );,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39500832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com