Reputation: 65
Ok, so I want to modify data based on what is being received here. All the data that the server receives via the POST method is dealt with in chunks. This is the HTML code:
<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');
}
Now in my server.js file I have node.js set up and all I want to do is if the incoming data =="hello", replace with "hello there", if incoming data=="what's up" replace with "the sky" else "good morning".After Ive modified the data I need to append it into the "hi_log.txt" file.
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);
});
}
But it doesn't work and I don't know how to proceed. I am very new at node.Can someone please help me with this and suggest some good documentation where i can understand this?
Upvotes: 0
Views: 98
Reputation: 340
Check the localeCompare documentation here
Return value A negative number if referenceStr occurs before compareString; positive if the referenceStr occurs after compareString; 0 if they are equivalent.
So you should use something else like:
if (body.includes("hello")) {
body = "hello there";
} else if(body.includes("what\'s up")) {
body = 'the sky';
} else {
body = 'good morning';
}
Upvotes: 0
Reputation: 468
Try this :
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);
});
Upvotes: 1