0

I am new to Nodejs, writing a very simple app with a function that makes an API call to another service running locally.

Code looks like this:

var request = require('request');

module.exports = {

tokenize: function(text){

        console.log("Request to tokenize.");

        var ServerEndpoint = 'http://localhost:3002/id/'+text;
        var secureresponse = "Server didn\'t respond.";
        var req = request.get(ServerEndpoint, card, function(err, response, body){
            if (!err && response.statusCode == 200){
                secureresponse = body;
            }else{
                secureresponse = "Server didn\'t respond.";
            }
        }).end();

        return secureresponse;

    }
};

Then running the tokenize function always returns "Server didn't respond.", while putting a console.log(body) right below "secureresponse = body;" does print the body on the console.

What am I missing?

Thanks!

Fede E.
  • 2,118
  • 4
  • 23
  • 39
  • @SLaks if it enters the "if (!err && response.statusCode == 200){" doen't that mean that is already got a response? cause it has the 200 status code... – Fede E. Apr 27 '18 at 19:04
  • Yes, but you're trying to return the value before the response. – SLaks Apr 27 '18 at 19:04
  • how are you calling this function ? pls. SLaks is right you are returning before response – Muhammad Usman Apr 27 '18 at 19:10
  • You can return a promise and use async/await to wait for the response – Muhammad Usman Apr 27 '18 at 19:10
  • to get proper result, use callback or promise – abdulbarik Apr 27 '18 at 19:10
  • @SLaks Ah, yeah, that console.log prints at after returning. How can I go with that and return the body instead? I checked the question you linked, but it's a little different... my case uses the "request library". Mind helping me? – Fede E. Apr 27 '18 at 19:11
  • Which library you use makes no difference. You need to learn how to write asynchronous code. https://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks Apr 27 '18 at 19:21
  • @SLaks thanks man, that post helped. I made it with a promise and it works perfectly. Thanks again. – Fede E. Apr 27 '18 at 19:36

0 Answers0