【问题标题】:Why I can't change the variable value from callback event?为什么我不能从回调事件中更改变量值?
【发布时间】:2018-09-06 05:16:21
【问题描述】:

情景一(问题)


POST 请求到 /radikpidr

headers: nothing special

body: pidr=radik

来自 /radikpidr 的 POST 响应

headers: nothing special

body: pidr=radik

期望(未达到):

将请求正文内容打印到控制台中。

现实(沮丧):

看起来,变量 [body] 自初始化以来没有改变。

注意:

我已经得到了响应我请求的请求正文内容,如果不更改正文(变量)是不可能实现的


const app = require("express")();

let body = "not as expected";

app.post("/radikloh", (req,res)=>{
    req.on("data",function(chunk){
        body = chunk.toString();
    });
    
    console.log(body)//"not as expected"

    req.on("end",function(){
        res.send(body);
    });

    console.log(body)//"not as expected"
});

app.listen(process.env.PORT);

场景二(一种解决方案)


POST 请求到 /radikpidr

headers: nothing special

body: pidr=radik

来自 /radikpidr 的 POST 响应

headers: nothing special

body: pidr=radik

期望(MET):

将请求正文内容打印到控制台中。

现实(或多或少令人满意):

正如预期的那样


const app = require("express")();

let body = "not as expected";

function buff (input){
    body = input;
}

app.post("/radikloh", (req,res)=>{
    req.on("data",function(chunk){
        body = chunk.toString();
        buff(body);
    });
    
    console.log(body)//"pidr=radik"
    
    req.on("end",function(){
        res.send(body);
    });
    
    console.log(body)//"pidr=radik"
});

app.listen(process.env.PORT);

问题是为什么?

我认为这是因为回调函数作用域,但在此示例中它可以正常工作:

function a (cb){
    cb("It worked just FINE");
}
function b (){
    let body = "not as expected";
    
    a(function(seter){
        body = seter;
    });
    
    console.log(body);//THE OUTPUT: "It worked just FINE"
}

甚至在这个:

let body = "not as expected";
function a (cb){
    cb("It worked just FINE");
}
function b (){

    
    a(function(seter){
        body = seter;
    });
    
    console.log(body);//THE OUTPUT: "It worked just FINE"
}

【问题讨论】:

  • 当您在第一种情况下在此行 body = chunk.toString(); 之后记录正文并在第二个日志中在此行 body = chunk.toString(); 之后以及在 buff 函数中在 body = input; 之后记录正文的值时会发生什么?
  • 你试过var body = "not as expected";
  • 是的,我试过了。如果我从回调函数中打印body,它将在两种情况下都按预期工作,无论变量类型(var 或 let)如何。

标签: javascript node.js express asynchronous scope


【解决方案1】:

您可以在节点网站上查看有关 request body 的信息

let body = [];
request.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has the entire request body stored in it as a string
});

您在发出 POST 请求时是否发送数据?如果 body 保持不变,那么它可能没有进入 req.on('data'.. 函数

【讨论】:

  • 除了修复代码和提供资源之外,您可能应该回答答案中的问题。
  • 你是对的。在触发 req.on 事件之前使用 body 变量(在这种情况下我正在打印到控制台)导致的这种后果。我通过使用 console.log(body) 上的超时功能检查了这个版本,它按预期工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
相关资源
最近更新 更多