【发布时间】: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