如何修复节点中的"Reference Error: message is not defined".js



我是node.js的新手,我需要解析名为"message.txt"的文件中的请求体。当我在控制台上记录消息变量时,这很好。代码很简单,首先,它创建一个服务器,然后在post方法上接收一个请求,然后将其保存到名为"message.txt"的文件中。我曾尝试更改变量名,但仍然无法解决错误。

const http = require('http');
const fs = require('fs');
const server = http.createServer((req,res)=>{
const url= req.url;
const method = req.method;
if(url=='/'){
res.write('<html>');
res.write('<head><title>enter message</title><head>');
res.write('<body><form action="/message" method="POST"><input type="text" name="message"><button type="submit">submit</button></form></body>');
res.write('</html>');
return res.end();
}
if(url=='/message'&&method=='POST'){
const body =[];
req.on('data',(chunk)=>{
body.push(chunk);
console.log(body)
});
req.on('end',()=>{
const parsedBody = Buffer.concat(body).toString();
// console.log(parsedBody);
const message = parsedBody.split('=')[1];
//console.log(messsage)
});
fs.writeFileSync('message.txt',message);
res.statusCode = 302;
res.setHeader('Location','/')
return res.end();
}
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head><title>my first page!</title><head>');
res.write('<body><h1>hello from node js</h1></body>');
res.write('</html>');
res.end();
});    
server.listen(3000)

If块应类似

if(url=='/message'&&method=='POST'){
const body =[];
req.on('data',(chunk)=>{
body.push(chunk);
console.log(body)
});
var message = '';
req.on('end',()=>{
const parsedBody = Buffer.concat(body).toString();
// console.log(parsedBody);
message = parsedBody.split('=')[1];
//console.log(messsage)
});
fs.writeFileSync('message.txt',message);
res.statusCode = 302;
res.setHeader('Location','/')
return res.end();
}

基本上,您的message变量的作用域仅限于req.on(),因此无法在外部访问。

常量变量是块范围的,请在此处了解更多信息。

在你的代码中,有这样一段:

req.on('end',()=>{
const parsedBody = Buffer.concat(body).toString();
// console.log(parsedBody);
const message = parsedBody.split('=')[1];
//console.log(messsage)
});
fs.writeFileSync('message.txt',message);

在这里,您将传递一个箭头函数作为req.on的第二个参数的回调
此箭头函数有自己的block scope

通过在该块范围内声明message变量,您将无法在它之外访问它

在您调用fs.writeFileSync的下一行中,您正试图这样做,访问该范围中不存在的message变量。

因此,在范围中移动该行:

req.on('end',() => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
fs.writeFileSync('message.txt', message); // here message can be accessed
});

您在回调函数之外使用本地定义的message变量。即使您全局定义了这个变量,在将其传递给fs.writeFileSync的过程中,该变量也不太可能没有NULL值。

因此,只需在定义message变量的行之后的req.on('end', () => { ... }中指定fs.writeFileSync('message.txt', message);即可。

相关内容

最新更新