LiteNode's logo

LiteNode

Docs GitHub logo
▶ Usage

Documentation

Body Parsing

LiteNode offers built-in support for parsing request bodies, streamlining the handling of JSON, URL-encoded form data, and multipart/form-data in request payloads. This functionality simplifies working with APIs and data interchange.

You can easily send JSON responses with the correct headers and manage POST requests that include JSON, URL-encoded form data, and multipart/form-data bodies.

Sending a JSON Response

Send JSON responses to client requests:

json

Description:

Sends a JSON response to the client with the provided data. This method sets the Content-Type header to application/json and sends the JSON representation of the provided data as the response body.

Signature:

json(data: any): void

Returns:

Example:

// Route to handle JSON response
app.get("/json", (req, res) => {
    // Send a JSON response with the message "Hello, LiteNode!"
    res.json({ message: "Hello, LiteNode!" })
})

Handling POST Requests

You can set a size limit on the request body for any type of data!

JSON

JSON Client

The provided HTML form, along with its corresponding script, is designed to collect user registration information and submit it to the server as JSON. The form includes fields for username, email, and password, all of which are required. When the user submits the form, the script prevents the default form submission, converts the form data to a JSON object, and sends it to the /register endpoint using a POST request. The script also handles and displays success or error messages based on the server's response.

<form onsubmit="handleSubmit(event)">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required />

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required />

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required />

    <button type="submit">Register</button>
</form>

<script>
    async function handleSubmit(event) {
        event.preventDefault() // Prevent default form submission

        const form = event.target
        const formData = new FormData(form)
        const userData = Object.fromEntries(formData.entries()) // Convert form data to an object

        try {
            const response = await fetch("/register", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(userData),
            })

            if (!response.ok) {
                const errorData = await response.json()
                throw new Error(errorData.error || "An error occurred during registration")
            }

            const responseData = await response.json()
            alert(responseData.message) // Display success message
        } catch (error) {
            alert("Error: " + error.message) // Display error message
        }
    }
</script>

JSON Server

The server-side code defines a route to handle user registration at the /register endpoint. When a POST request is received, the server processes the request body, which is expected to be in JSON format. The server performs the following tasks:

  1. Data Extraction and Validation: Extracts username, email, and password from the request body. It validates that all required fields are present.
  2. Error Handling: If any required fields are missing, the server responds with a 400 status code and an error message indicating the missing fields.
  3. User Registration: If validation is successful, the server proceeds with the user registration process, which may involve database operations.
  4. Success Response: On successful registration, the server sends a 201 status code with a JSON response indicating that the user was registered successfully.
  5. Error Response: If an error occurs during registration, the server responds with a 400 status code and an error message detailing the issue.

Optional: The request size is limited to 0.5MB to prevent excessively large payloads.

// Define a route to handle user registration
app.post(
    "/register",
    async (req, res, data) => {
        try {
            // Simulate user registration process
            const { username, email, password } = data
            // Validate user data (e.g., check for required fields)
            if (!username || !email || !password) {
                // If any required field is missing, throw an error
                throw new Error("Missing required fields")
            }
            // If all validation passes, register the user
            // Database operations...
            res.writeHead(201, { "Content-Type": "application/json" })
            res.end(JSON.stringify({ message: "User registered successfully" }))
            // Or simply write after database operations...
            res.status(201).json({ message: "User registered successfully" })
        } catch (error) {
            // Handle any errors that occur during registration
            console.error("Error registering user:", error.message)
            res.writeHead(400, { "Content-Type": "application/json" })
            res.end(JSON.stringify({ error: error.message }))
            // Or simply write
            res.status(400).json({ error: error.message })
        }
    },
    0.5 // Set maximum request size to 0.5MB = 512KB (optional, default is 1MB)
)
Information SVG Writing:
res.writeHead(201, { "Content-Type": "application/json" })
res.end(JSON.stringify({ message: "My message" }))
Is the same as writing:
res.status(201).json({ message: "My message" })

URL-encoded form data

URL-encoded Client

The following HTML form is designed to submit data to the /create-file endpoint using URL-encoded form data. It employs bracket notation in the input names to match the expected structure on the server side.

Form Fields
  1. Title: A text input for the file's title, named file[title].
  2. Description: A textarea for the file's description, named file[description].
  3. Image URL: A URL input for the file's image URL, named file[image].
  4. Publish Date: A date input for the file's publication date, named file[publish_date].
  5. Tags: A text input for comma-separated tags associated with the file, named file[tags].
Form Attributes
Purpose

This form allows users to input and submit detailed information about a file. Each field corresponds to a specific piece of data that the server will process, utilizing the bracket notation to structure the incoming data correctly.

<form action="/create-file" method="POST" enctype="application/x-www-form-urlencoded">
    <label for="file_title">Title:</label>
    <input type="text" id="file_title" name="file[title]" required />

    <label for="file_description">Description:</label>
    <textarea id="file_description" name="file[description]" required></textarea>

    <label for="file_image">Image URL:</label>
    <input type="url" id="file_image" name="file[image]" required />

    <label for="file_publish_date">Publish Date:</label>
    <input type="date" id="file_publish_date" name="file[publish_date]" required />

    <label for="file_tags">Tags (comma-separated):</label>
    <input type="text" id="file_tags" name="file[tags]" />

    <button type="submit">Create File</button>
</form>

URL-encoded Server

The following server-side code snippet handles POST requests to the /create-file endpoint. It processes URL-encoded form data, extracting and utilizing the submitted file-related information.

app.post("/create-file", (req, res, data) => {
    const { file } = data
    // Proceed with the file's data
})
Functionality
  1. Endpoint Definition: The app.post("/create-file", ...) method sets up a route to handle POST requests at the /create-file URL.
  2. Request Handling: When a request is received:
    • Data Extraction: The data parameter represents the parsed form data. The file object within data contains the details submitted via the form.
    • Processing: The code can then access properties such as file[title], file[description], file[image], etc., based on the structure defined in the HTML form.
  3. Further Actions:
    • Data Validation: You would typically include validation to ensure that all required fields are present and correctly formatted.
    • Database Operations: If needed, the server can save the extracted data to a database or perform other processing tasks.
    • Response Handling: After processing the data, the server should respond to the client, indicating success or providing error information.
Notes

multipart/form-data

Client-Side Code

<form action="/set-images" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple />
    <button type="submit">Upload</button>
</form>

Description:

This HTML form allows users to upload multiple files to the server.

Server-Side Code

app.post(
    "/set-images",
    async (req, res, data) => {
        const { files } = data
        try {
            for (const file of files) {
                const filePath = `images/${file.filename}`

                await writeFile(filePath, file.body)
            }
            res.redirect("/set/images")
        } catch (err) {
            console.error("Error writing files:", err)
            res.status(500).send("Internal Server Error")
        }
    },
    5
)

Description:

This server-side code handles file uploads sent to the /set-images endpoint.

meros

LiteNode internally uses the meros library to handle multipart/form-data submissions efficiently. meros is an extremely lightweight library, with a size of just 1KB, making it ideal for handling file uploads without adding significant overhead.

For each uploaded file, meros provides access to the following properties:

For more details about the meros library, you can visit its npm page.

Content