Javascript 响应体的concat缓冲区未写入文件,甚至显示在console.log上

Javascript 响应体的concat缓冲区未写入文件,甚至显示在console.log上,javascript,node.js,fs,Javascript,Node.js,Fs,我尝试使用node.js和fs测试req/res,并使用下面的代码将输入写入文件 我尝试使用console.log(),但没有显示引用已解析的主体(数据集中)。终端输出上只显示块 const server = http.createServer((req, res) => { const url = req.url; const method = req.method; if (url === '/') { res.write('<html&g

我尝试使用node.js和fs测试req/res,并使用下面的代码将输入写入文件

我尝试使用
console.log()
,但没有显示引用已解析的主体(数据集中)。终端输出上只显示块

const server = http.createServer((req, res) => {
    const url = req.url;
    const method = req.method;
    if (url === '/') {
        res.write('<html>');
        res.write('<head><title>Enter a Message</title></head>');
        res.write('<body><form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form></body>');
        res.write('</html>');
        return res.end();
    }
    if (url === '/message' && method === 'POST') {
        const body = [];
        req.on('data', (chunk) => {
            console.log(chunk);
            body.push(chunk);
        });
        req.on('end', () => {
            const parsedBody = Buffer.concat(body).toString();
            const message = parsedBody.split('=')[1];
            fs.writeFileSync('message.txt', message);


            console.log(parsedBody); // dont shows on terminal output
        });
        res.statusCode = 302;
        res.setHeader('Location', '/');
        return res.end();
    }

    res.setHeader('Content-Type', 'text/html');
    res.write('<html>');
    ...
    res.write('</html>');
    res.end();
});

Whats the problem I did to get it? I believe I am  doing something wrong, but what?

thanks in advice.
const server=http.createServer((req,res)=>{
const url=req.url;
const method=req.method;
如果(url=='/')){
res.write(“”);
res.write(“输入消息”);
res.write('Send');
res.write(“”);
返回res.end();
}
如果(url=='/message'&&method==='POST'){
常量体=[];
请求on('数据',(块)=>{
console.log(块);
推(块);
});
请求开启('end',()=>{
const parsedBody=Buffer.concat(body.toString();
const message=parsedBody.split('=')[1];
fs.writeFileSync('message.txt',message);
console.log(parsedBody);//在终端输出上不显示
});
res.statusCode=302;
res.setHeader('Location','/');
返回res.end();
}
res.setHeader('Content-Type','text/html');
res.write(“”);
...
res.write(“”);
res.end();
});
我是怎么弄到的?我相信我做错了什么,但是什么呢?
谢谢你的建议。

只是一个想法:尝试在
res.write(“”)
之后删除最后一个
res.end()
并查看套接字是否在removig接收到最后一个块之前关闭。不工作,但在工作之前添加return。谢谢你看到你做了两次res.end()了吗?在接收到最后一个区块后,在请求处理程序的末尾执行一次。在接收到最后一个块之前将调用此块。我敢肯定这就是给你带来麻烦的原因。可能使用
if-else
处理不同的请求?我知道了,我会按照你说的使用check。谢谢