0

I am getting http post message, but can't get the body outside the getRawBody function.

Here is my code:

getRawBody(req, function(err, body) {
    for (var key in req.queries) {
     var value = req.queries[key];
      resp.setHeader(key, value);
    }
    string = params.body = body.toString();
    string=querystring.parse(string);
    data=string.data;
    object=JSON.parse(data);
    console.log(object)     
    resp.send(JSON.stringify(object, null, '    '));
});

console.log(object);

The first console log outputs the correct JSON like

{ id: 'ddeklj' }.

But the second console log outputs is undefined.

My question is: How can I get the variables object from the function?

creimers
  • 4,975
  • 4
  • 33
  • 55
jeffdeng
  • 61
  • 4
  • Do you try init variable outside function or init as *window.object* ? – Vitalii Mar 26 '19 at 09:33
  • Callbacks, that's what you need. – Script47 Mar 26 '19 at 09:34
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Script47 Mar 26 '19 at 09:35
  • Also, if this is async function, try use Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Vitalii Mar 26 '19 at 09:35

2 Answers2

0

It looks like you are using AliCloud Function Compute and are trying to get the value of the body from the http request.

AliCloud's functions send the body in as a buffer and their example code that you are referencing is a bit confusing. You can extract the body from the req by doing something like this :

var getRawBody = require('raw-body');
module.exports.handler = async function (req, resp, context) {

  var getBody = await getRawBody(req);
  var bodyToString = getBody.toString();

  console.log(bodyToString );
}
HodgePodge
  • 15
  • 1
  • 6
-1

Declare Variable outside the function, and then initialize it inside the function

let a;
Function getData(){
a = 20;
}
getData();
console.log(a);