1

我正在使用在 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
4

1 回答 1

1

问题是您正在覆盖全局 JSON 对象。

这将工作得很好:

var parseJSON = function(MyJSON, cb){

    var parsed = JSON.parse(MyJSON);
    cb(parsed);

};
于 2012-12-07T06:36:15.340 回答