[英]Node.js: Howto close response/request while retrieving data (chuncks)
[英]Modifying data in node.js when its coming in as chuncks
好的,所以我想根据这里收到的内容修改数据。 服务器通过 POST 方法接收的所有数据都以块的形式处理。 这是 HTML 代码:
<button id='helloButton'>Greet the server with hello!</button>
<button id='whatsUpButton'>Greet the server with what's up!</button>
helloButton.onclick = function() {
xmlHttp.open('POST','/greeting', true);
xmlHttp.setRequestHeader('Content-type','text');
xmlHttp.send('hello');
}
whatsUpButton.onclick = function() {
xmlHttp.open('POST','/greeting', true);
xmlHttp.setRequestHeader('Content-type','text');
xmlHttp.send('what\'s up');
}
现在在我的 server.js 文件中,我设置了 node.js,我想要做的就是如果传入数据 ==“hello”,则替换为“hello there”,如果传入数据==“what's up”替换为“天空”否则“早上好”。我修改了数据后,我需要将其附加到“hi_log.txt”文件中。
if (request.method === 'POST' && request.url === '/greeting') {
let body=[]
request.on("data",chunk=>{
body.push(chunk);
});
request.on("end",chunk=>{
var newbody='';
body=Buffer.concat(body).toString()+"\n";
console.log(body);
if (body.localeCompare("hello")){
body.replace(body,"hello there \n");
}
else if(body.localeCompare("what\'s up")){
body.replace(body,'the sky \n');
}
else{
body.replace(body,'good morning \n');
}
fs.appendFileSync("hi_log.txt",body);
response.end(body);
});
}
但它不起作用,我不知道如何继续。 我在节点上很新。有人可以帮我解决这个问题并建议一些我可以理解的好的文档吗?
尝试这个 :
request.on("end", chunk => {
body = Buffer.concat(body).toString();
console.log(body);
if (body === "hello") {
body = "hello there";
} else if(body === "what\'s up") {
body = 'the sky';
} else {
body = 'good morning';
}
body += ' \n';
fs.appendFileSync("hi_log.txt",body);
response.end(body);
});
在此处查看 localeCompare 文档
返回值 如果 referenceStr 出现在 compareString 之前,则为负数; 如果 referenceStr 出现在 compareString 之后,则为正; 如果它们相等,则为 0。
所以你应该使用其他类似的东西:
if (body.includes("hello")) {
body = "hello there";
} else if(body.includes("what\'s up")) {
body = 'the sky';
} else {
body = 'good morning';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.