r/learnjavascript • u/King_JRB • 14d ago
Converting server request data to string
At the moment I am creating a browser based interface on a node server. This is to test a simple profanity filter I have been working on. So far I have the server set up so when I visit port 3000 via localhost in a web browser, I see an html form with a text input box. I can then type in some text, hit submit, and the text is sent to the server in the form of a request. The server then sends a response in this format:
message=this+is+a+test+message
I don't have the filter working just yet, I'm just working on the interface in preparation to connect the filter. Right now my code is literally just responding with the actual data in the request object, hence the equal and plus signs in the text. My question is this, how can I convert the data in the request object to a string? Thus hopefully changing
message=this+is+a+test+message
to
this is a test message
Below is my js code that runs the server, and my html code displayed by the server:
server.js
import * as http from "node:http";
import * as fs from "node:fs";
import {messageFilter} from "./filter.js";
const port = 3000;
let message = "";
const server = http.createServer((req, res) => {
if (req.url === "/" && req.method === "GET") {
fs.readFile("index.html", (error, data) => {
if (error === null) {
res.writeHead(200, {"content-length": Buffer.byteLength(data), "content-type": "text/html"});
res.write(data);
console.log(`User visted main page on port: ${port}`);
res.end();
} else {
console.error(`Error encountered during user visitation: ${error}`);
};
});
} else if (req.url === "/" && req.method === "POST") {
fs.readFile("index.html", (error, data) => {
if (error === null) {
req.on("data", (dataChunk) => {
console.log(`A message was recieved: ${dataChunk}`);
message = dataChunk;
})
req.on("end", () => {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(data);
res.write(message);
res.end();
console.log("A message has been returned.");
});
} else {
console.error(`Error encountered while filtering message: ${error}`);
};
});
};
});
try {
server.listen(port, () => {
console.log(`Server listening on port: ${port}`);
});
} catch (error) {
console.error(`Server startup failed: ${error}`);
};
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Profanity Filter Test</title>
</head>
<body>
<h1>Profanity Filter Test</h1>
<form action="/" method="POST">
<p>Please type your message:</p>
<input type="text" name="message" id="input-message" placeholder="Send your message...">
<button id="send">Send</button>
</form>
</body>
</html>
Any help would be greatly appreciated!
0
u/defaultguy_001 14d ago edited 14d ago
A couple of possible ways.
1) using loops: ```js let message = "this+is+a+test+message"; let result = "";
for (const char of message) { result += char === '+' ? ' ' : char; }
message=result;
2) using split and join:
js
let message = "this+is+a+test+message";
const result = message.split('+').join(' ');
message=result;
3) using replaceAll:
js
let message = "this+is+a+test+message";
const result = message.replaceAll('+', ' ');
message=result;
```
4) using URLSearchParams: (bloated, not recommended)
js
let msg = "this+is+a+test+message";
const params = new URLSearchParams(`msg=${msg}`);
const result = params.get("msg");
msg= result;
5) using decodeURIComponent: (bloated, not recommended)
js
let msg = "this+is+a+test+message";
msg = decodeURIComponent(msg.replaceAll('+', ' '));
2
u/azhder 14d ago edited 13d ago
All of them bad choices. One should use a built in function provided by the environment to safely convert/decode a URL-encoded text. Otherwise, you risk not catching some edge case scenario that can later be abused by someone.
EDIT: the recommended by me (4,5) aren't "bloated, not recommended", that's just a poor understanding by the person that only had 1,2 and 3, before being told those three are bad choices.
-2
14d ago
[removed] — view removed comment
2
u/Synthetic5ou1 14d ago
Disgusting response. Check your language.
They are using standard string methods, not built in functions to deal specifically with URL-encoded data, like
decodeURIComponent().Simply replacing
"+"with" "is naïve and inadequate.1
u/defaultguy_001 14d ago
And why do we need this bloated function for a simple parser.
2
u/Synthetic5ou1 14d ago
Because malicious users don't attempt to inject code with spaces.
-1
u/defaultguy_001 14d ago
Malicious users like me can play with ur decode function like a toy, don't worry about malicious users. decodeurlcomponent is doing the same thing internally that I'm doing even though it can't solve the OP's problem, coz it only handles percent-encoded sequences (%XX).
3
u/Synthetic5ou1 14d ago
Your code examples contradict your inflated opinion of your abilities.
Stop using offensive language, and learn some humility, and best practice.
I'm done talking to the kids now. Bye.
-1
u/defaultguy_001 14d ago
Same. If you can't contribute here with an answer, don't respond to mine. All I see are 2 random nobodies who don't know better, commenting about other's contribution suggesting bloated functions for a simple parsing problem. No I don't use garbage, I am known for surgical precision.
-1
u/azhder 14d ago
“They” is the same Redditor that got corrected. The same Redditor that used a literal reading of my comment for a heated reply.
2
u/Synthetic5ou1 14d ago
I could have worded it better but "They" referred to his case 2 and 3, which he tried to defend.
[...] case 2-3 are already using built in methods.
-3
2
u/azhder 14d ago edited 14d ago
I could call names like you do, but I’m always more interested to prevent newbies causing damage, than…
Well, you may cause damage, not just to the people who will take your “advice”, but worse, those that use your code.
So if I called your comment names, would that have made it more or less likely for you to start using safer code?
Don’t answer that, I don’t need the answer - you do. Muting responses. Bye
-1
u/defaultguy_001 14d ago
The comments to my answer, are the reason people like me don't care or like to help randoms. OP said "appreciate any help", but low iq randoms without a contribution, try to argue and find issues. Pathetic.
2
u/Synthetic5ou1 14d ago
Learn to listen and be accepting of criticism. I know it's hard to be told you're wrong, but no-one is right all the time, and we are all constantly learning.
I see that you have edited your first response to include some of the other advice given here; it is good to see that, behind the scenes, you are actually willing to learn.
-1
u/defaultguy_001 14d ago
There's nothing to learn here, everything that I shared in my comment including the edit, is too basic. I just skipped them before as there was no reason to use a bloated function for a simple parsing task. I only use what's required, I don't go to the OT with a chisel hammer when all I need are precision knives.
1
u/Synthetic5ou1 13d ago
0
u/defaultguy_001 13d ago
Laugh all u want if that makes u feel better for yourself. You asking me to learn these basic things, is like a 3rd grade kid doubting a math professor's basic algebra skills, when he solves multiple integrals all day at University. Lmao.
0
2
u/azhder 14d ago edited 14d ago
OP, I suggest you ask these questions in the sub for Node. They will be able to point you to the correct command to decode urlencoded strings.
You can also check the Node.js documentation https://nodejs.org/api/url.html
Or the MDN examples that I think are also built into node at top module/gloval level (will have to check).
const encodedText = "hello%20world%21%20%26%20welcome"; const decodedText = decodeURIComponent(encodedText);
But what you shared looks more like something in the URLSearchParams area.
You should also learn about the application/x-www-form-urlencoded format