ppedrazzi
ppedrazzi

Reputation: 787

Accessing the HTTP GET JSON Object

I am getting my feet wet with Meteor's HTTP methods.

As a test, I am hitting Twitter's api with a method on the server, as follows:

"twitter_user": () ->
   Meteor.http.get("https://api.twitter.com/1/users/show.json", {screen_name:"ppedrazzi"})

On the client, I call the method as follows:

  twitterUser = Meteor.call("twitter_user")

When trying to access the twitterUser object, it shows as undefined. I was expecting to be able to use twitterUser.data.id or twitterUser.data.name to grab the fields from the resulting JSON, but no luck (since the object does not exist).

Incidentally, if I drop the URL into the browser, I get a JSON object on the page, see example here: https://api.twitter.com/1/users/show.json?screen_name=ppedrazzi

Upvotes: 2

Views: 2252

Answers (1)

mquandalle
mquandalle

Reputation: 2598

You should use an async call to your method:

Meteor.call "twitter_user", (error, result) -> 
  twitterUser = result

Citation from the documentation:

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn't have fibers, so there is not actually any way it can block on the remote execution of a method.

Note that in this particular case, you can run Meteor.http.get directly on the client:

Meteor.http.get(
   "https://api.twitter.com/1/users/show.json", 
   screen_name:"ppedrazzi",
   (error, result) -> twitterUser = result 
)

Upvotes: 1

Related Questions