[英]Why I can't change the variable value from callback event?
headers: nothing special
body: pidr=radik
headers: nothing special
body: pidr=radik
Print request body content into the console.
将请求正文内容打印到控制台中。
Varibale [body] was not changed since initialisation, as it seems.
自初始化以来,Varibale [body]并未改变。
I've got the request body content in response to my request, which is imposible to achieve without changing body (variable)
我已经收到了响应我的请求的请求正文内容,这是在不更改正文的情况下无法实现的(变量)
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);
headers: nothing special
body: pidr=radik
headers: nothing special
body: pidr=radik
Print request body content into the console.
将请求正文内容打印到控制台中。
Just as expected
符合预期
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);
I thought this is because of a callback function scope but it works fine in this expample: 我认为这是由于回调函数作用域引起的,但在此示例中可以正常工作:
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"
}
And even in this: 即使这样:
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"
}
you can check this out on node site about 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
});
Are you sending data when you make a POST request ? 发出POST请求时是否正在发送数据? if body remains the same then it may be not entering the req.on('data'.. function
如果主体保持不变,则可能未输入req.on('data'..函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.