简体   繁体   English

如何将函数内部的变量作为全局变量获取?

[英]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. 我正在获取http发布消息,但是无法在getRawBody函数之外获取正文。

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 第一个控制台日志输出正确的JSON,例如

{ id: 'ddeklj' } . { id: 'ddeklj' }

But the second console log outputs is undefined . 但是第二个控制台日志输出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函数计算,并且正在尝试从http请求中获取正文的值。

AliCloud's functions send the body in as a buffer and their example code that you are referencing is a bit confusing. AliCloud的函数将主体作为缓冲区发送,您要引用的示例代码有些混乱。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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