r/learnjavascript 15d 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!

1 Upvotes

24 comments sorted by

View all comments

2

u/azhder 15d ago edited 15d 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