简体   繁体   中英

How to get the variables inside a function as a global variables?

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?

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 );
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM