0

I have a simple http.get request to external api. How can I access id and name variables from another function? Thanks!

app.use(function *(next){

	var name = '';
	var id = '';

	var options = {
		host: 'www.website.com',
		path: '/json/somedata',
		metohd: 'GET'
	};
	http.get(options, function(res) {

		var body = '';

		res.on('data', function(chunk) {
			body+=chunk;
			console.log(body);
		})
		res.on('end', function() {
			var parsed = JSON.parse(body);
            id = parsed.id;
            name = parsed.name;
		})
	})
});

1
  • The http library is pretty low level. I recommend you have a look at request on npm, it behaves a bit more like you'd expect. Commented Dec 14, 2016 at 18:14

1 Answer 1

1

I guess you are using the npm module express, with the syntax you have there.

Your answer depends on where you are looking to use id and name. If you are trying to use it in a route or middleware after this one a common way to solve that problem is to attach the properties (in this case name and id) to the request. Remember to call next after you are finished otherwise express will not know you have finished all your processing

I've given a quick example below:

app.use(function (req, res, next){

   var options = {
       host: 'www.website.com',
       path: '/json/somedata',
       method: 'GET'
   };
   http.get(options, function(getResponse) {

    var body = '';

    getResponse.on('data', function(chunk) {
        body+=chunk;
        console.log(body);
    })
    getResponse.on('end', function() {
        var parsed = JSON.parse(body);
        req.id = parsed.id;
        req.name = parsed.name;
        next();

    })
    })
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.