2

I have two node servers (A + B) and both use Expressjs.

From one I use Request (https://github.com/mikeal/request) to make a GET request to the other:

//A server
app.get('/:id', function(req, res) {
  request('http://localhost:8080/api/' + req.params.id, function (error, response, body) {
    console.log(body);
  })
});

and the other is:

//B server
app.get('/api/:id', function(req, res) {
  res.json(200, {url: "http://www.google.co.uk"});  
});

As you can see, A is making a request to B and B returns a json result. However, I'm not sure how to deal with the response in A. console.log(body) prints the complete json but how can I access the url sent from B?

I have tried body.url but no luck

2
  • 1
    try JSON.parse on the result, prior to accessing it like an object. Commented May 11, 2014 at 17:54
  • that's done the trick - put it as an answer if you like and I will tick Commented May 11, 2014 at 17:56

1 Answer 1

2

The JSON result is a string. You must first parse it via JSON.parse, prior to accessing it like an object:

var url = JSON.parse(body).url;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.