我正在使用在npm上找到的请求模块,我想知道是否有可以绑定的结束事件。我问的原因是因为我要求一个JSON,如果我在得到响应后尝试直接使用JSON.parse,我会收到错误。代码看起来像这样。
var parseJSON = function(JSON, cb){
var parsed = JSON.parse(JSON);
cb(parsed);
};
request(url, function(error, response, body) {
parseJSON(body, function(bodyObj){
// do stuff with bodyObj...
});
});
尝试这样做,会出现以下错误......
var parsed = JSON.parse(JSON);
^
has no method 'parse'
at parseJSON (/home/stephen/Desktop/redditjs/reddit.js:31:20)
at Requester.collector [as _callback] (/home/stephen/Desktop/redditjs/reddit.js:43:5)
at Request.init.self.callback (/home/stephen/node_modules/request/main.js:122:22)
at Request.EventEmitter.emit (events.js:99:17)
at Request.<anonymous> (/home/stephen/node_modules/request/main.js:661:16)
at Request.EventEmitter.emit (events.js:126:20)
at IncomingMessage.Request.start.self.req.self.httpModule.request.buffer (/home/stephen/node_modules/request/main.js:623:14)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23
答案 0 :(得分:1)
问题是你要覆盖全局JSON对象。
这样可以正常工作:
var parseJSON = function(MyJSON, cb){
var parsed = JSON.parse(MyJSON);
cb(parsed);
};