简体   繁体   中英

Multiple responses on node.js restler call

I've created a library for sending REST requests:

var rest = require('restler');
module.exports = {
  beginSession: function()
  {
    var options = {
        method: "GET",
        query: {begin_session: '1'}};
    rest.get('http://countly/i', options).
        on('complete', function(data, response){
            console.log('Status: ' + response.statusCode);
        });
  }
};

The problem is that every time I use the library and the call is responded, the 'on complete' is called multiple times: 1st use of method will call 'on complete' just once, 2nd use of method will call 'on complete' twice and so on....

What Am I doing wrong?

Thanks Jose

I was struggling with this one as well. but didn't find an answer on the internet. I finally figure it out though. It was caused by the 'complete' event being registered every time the your rest.get() is called.

My solution is to use .once() instead of .on(). For example:

var rest = require('restler');
rest.get('url_to_fetch').once('complete', function(rtn, rsp){
     ....blah blah....
});
// refer here http://nodejs.org/api/events.html#events_emitter_once_event_listener

Hopefully this helps.

TL;DR: Bug in restler, quick fix until npm is updated: add git master to package.json

The real problem here is that some changes to the event API in node 0.10 results in restler refiring old event listeners as described in https://github.com/danwrong/restler/issues/112 .

End of august this was fixed in https://github.com/danwrong/restler/pull/113 . While we wait for a proper npm release it works for me by using the current git head.

"restler": "git://github.com/danwrong/restler.git#9d455ff14c57ddbe263dbbcd0289d76413bfe07d"

DISCLAIMER: I don't know what is broken in this version or why it is not released yet. I did not go trough the issues or diffs since last release to find out.

UPDATE Aug 2014: There was a npm release since then, it seems to include the fix.

This is because you attach a new event for each call. Try to unbind event first.

An exception occurring in your callback handler for a JSON request can also cause this behaviour.

See the pull request here for a solution for that: https://github.com/danwrong/restler/pull/94

Please check out v3.2.2. Upgrade your package.json:

npm install restler --save

It solved this issue for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM