2013-09-12 4 views
0

Я использую Express в первый раз, и у меня возникает проблема. Я пытаюсь изменить this tutorial и для моих целей, но я использую Redis вместо MongoDB.Экспресс REST API не возвращает целочисленный массив

Вот мой код:

redisSource.js:

var redis = require ("node-redis"); 

RedisSource = function() { 
     this.r_client = redis.createClient(); 

     this.getParents = function (circuit_id, cb) { 
       this.r_client.smembers('circuit.parents_of:' + circuit_id, function(err, reply){ 
         console.log("Reply: " + reply); 
         cb(err, reply); 
       }); 
     } 
} 

exports.RedisSource = RedisSource; 

fetch.js:

Fetch = function(app) { 
     var RedisSource = require ('./redisSource').RedisSource; 
     var redisSource = new RedisSource(); 

     app.get('/parents/:id', function(req, res) { 
       redisSource.getParents(req.params.id, function (error, parents) { 
         console.log ("Response in Fetch main: " + parents); 
         res.send(parents); 
       }); 
     }); 

     app.get('/test', function (req, res) { 
       res.send('Hello, world!'); 
     }); 
}; 

exports.Fetch = Fetch; 

app.js:

/** 
* Module dependencies. 
*/ 

var express = require('express'); 
var routes = require('./routes'); 
var user = require('./routes/user'); 
var http = require('http'); 
var path = require('path'); 

var app = express(); 

// all environments 
app.set('port', process.env.PORT || 3000); 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'jade'); 
app.use(express.favicon()); 
app.use(express.logger('dev')); 
app.use(express.bodyParser()); 
app.use(express.methodOverride()); 
app.use(app.router); 
app.use(express.static(path.join(__dirname, 'public'))); 

// development only 
if ('development' == app.get('env')) { 
    app.use(express.errorHandler()); 
} 

app.get('/', routes.index); 
app.get('/users', user.list); 

var Fetch = require('./fetch').Fetch; 
var FetchService = new Fetch(app); 

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

При запуске приложения, я получаю следующее:

GET http://ironsides.zayo.com:3000/test 
> Hello, world! 

Что является то, что я ожидал. Но когда я пытаюсь другой вызов:

GET http://ironsides.zayo.com:3000/parents/12115 
> [ [ 49, 53, 50, 55, 51 ], [ 49, 53, 50, 56, 56 ], [ 49, 53, 51, 48, 56 ], [ 49, 53, 51, 48, 57 ], [ 49, 53, 51, 49, 48 ], [ 49, 53, 51, 49, 49 ], [ 49, 53, 51, 50, 56 ], [ 49, 53, 51, 50, 57 ], [ 49, 53, 51, 51, 48 ], [ 49, 53, 51, 52, 49 ], [ 51, 51, 50, 54, 51 ] ] 

На консоли, я получаю это:

GET /parents/12115 200 74ms - 530b 
Reply: 15273,15288,15308,15309,15310,15311,15328,15329,15330,15341,33263 
Response in Fetch main: 15273,15288,15308,15309,15310,15311,15328,15329,15330,15341,33263 

Я ожидаю, что массив целых чисел, которые я вижу на консоли. Вместо этого я получаю массив массивов кодов символов ascii для этих целых чисел. Я действительно смущен. Я уверен, что я пропустил что-то простое.

+0

Вы пытались отправить результат как JSON? – max

+0

@max - Как JSON.stringify? Да, тот же результат. –

+0

Я имею в виду отправку как 'res.send ({родители: родители});' в 'fetch.js'. – max

ответ

0

между комментариями Макса и this thread, я понял это. Модуль «node-redis» возвращает буферы, а не строки. Если я переписать заявление:

console.log ("Response in Fetch main: " + parents); 

как

console.log (parents); 

Затем он возвращается как массив буферов. Поэтому я переписал redisSource.getParents(), как это:

this.getParents = function (circuit_id, cb) { 
      this.r_client.smembers('circuit.parents_of:' + circuit_id, function(err, reply){ 
        console.log("Reply: " + reply); 
        var string_reply = reply.map(function(item) { return item.toString('utf8'); }); 
        cb(err, string_reply); 
      }); 
    } 

Как вы можете видеть, это будет возвращать массив строк вместо массива буферов.

Смежные вопросы