为什么我无法从回调事件中更改变量值?

时间:2018-03-27 17:21:09

标签: javascript node.js express asynchronous scope

场景一(问题)

POST请求/ radikpidr

  

headers: nothing special

     

body: pidr=radik

来自/ radikpidr

的POST响应
  

headers: nothing special

     

body: pidr=radik

期望(NOT MET):

  

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

现实(令人沮丧的):

  

Varibale [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"
}

1 个答案:

答案 0 :(得分:0)

您可以在节点网站上查看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请求时是否正在发送数据?如果身体保持不变,那么它可能没有进入req.on('data'.. function