1

I'm beginning with node.js and i'm trying to do a simple request. I'm using "request": "^2.87.0"

       output = "Hello ";
        const h = {'content-type': 'application/json'};
        const u = weburl;
        const b = JSON.stringify({
            "username" : user,
            "password" : psw
        });
        request.post({
            headers : h,
            url : u,
            body : b
        },function(error,response,body){
            if (error)
                output+= error;
            else {
                var jsonbody = JSON.stringify(body); //jsonbody = "\"token\""
                jsonbody = jsonbody.substr(3,jsonbody.length-4); // jsonbody = token
                console.log(jsonbody);
                output += jsonbody;
            }
        });
        send_message(output);

The token is shown in the console, but the output is "Hello" instead of "Hello token"

Grublixx
  • 29
  • 1
  • 6
  • 1
    Why are you using `JSON.stringify`, only to then snip around at the result using string functions …? Makes little sense. What is the body supposed to contain in the first place? – CBroe Jul 30 '18 at 09:21
  • Does `request.post` probably work asynchronous? If yes, chances are that the `send_message(output);` is called before any results were fetched from the POST request. – feeela Jul 30 '18 at 09:25

1 Answers1

1

Call the "send_message()" inside the request, due to the asynchronous nature of js send_message() is called before completing the request

like this:

output = "Hello ";
        const h = {'content-type': 'application/json'};
        const u = weburl;
        const b = JSON.stringify({
            "username" : user,
            "password" : psw
        });
        request.post({
            headers : h,
            url : u,
            body : b
        },function(error,response,body){
            if (error)
                output+= error;
            else {
                var jsonbody = JSON.stringify(body); //jsonbody = "\"token\""
                jsonbody = jsonbody.substr(3,jsonbody.length-4); // jsonbody = token
                console.log(jsonbody);
                output += jsonbody;
                send_message(output); //<---- here
            }
        });

Hope this helps

Hello World
  • 2,673
  • 7
  • 28
  • 60