2016-09-14 5 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応答ステータスは整数である必要があります。これは、文字列、オブジェクト、配列、またはそのようにすることはできませんし、私はあなたが

res.sendStatus(reply);

確認応答変数をしようことがわかります。コードから100

から始める必要があります。 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

EDIT

あなたはフロントエンドにいくつかの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 ..ちょうど200から200に変更するか、または何でも...しかし100より小さい –

+0

実際に私は非常に簡単なビジターカウンターを実装しています。ここでは、URIによって集計された最後の5分間の訪問数を数えようとしています。私はubuntuで同じコードを試して、正しい出力を得ています。すなわち 3 ...最後の5分間の訪問数。 しかし私のMacでは、私はこのエラーが発生しています。 これが正しい方法でない場合、この番号をページに表示する方法を教えてください。ごめんなさい、これはノードで初めてのことです。 – ASP

関連する問題