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:
data
(any): The JSON data to be sent as the response body.- Returns: void
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:
- Data Extraction and Validation: Extracts
username
,email
, andpassword
from the request body. It validates that all required fields are present. - Error Handling: If any required fields are missing, the server responds with a 400 status code and an error message indicating the missing fields.
- User Registration: If validation is successful, the server proceeds with the user registration process, which may involve database operations.
- Success Response: On successful registration, the server sends a 201 status code with a JSON response indicating that the user was registered successfully.
- 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)
)
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
- Title: A text input for the file's title, named
file[title]
. - Description: A textarea for the file's description, named
file[description]
. - Image URL: A URL input for the file's image URL, named
file[image]
. - Publish Date: A date input for the file's publication date, named
file[publish_date]
. - Tags: A text input for comma-separated tags associated with the file, named
file[tags]
.
Form Attributes
- Method: The form uses the
POST
method to send data to the server. - Encoding Type: LiteNode automatically detects the encoding type! The
enctype="application/x-www-form-urlencoded"
is optional to ensure that the form data is submitted in URL-encoded format, which is compatible with traditional form submissions.
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
- Endpoint Definition: The
app.post("/create-file", ...)
method sets up a route to handle POST requests at the/create-file
URL. - Request Handling: When a request is received:
- Data Extraction: The
data
parameter represents the parsed form data. Thefile
object withindata
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.
- Data Extraction: The
- 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
- Data Structure: The
file
object is derived from the URL-encoded form data and will contain properties corresponding to the input names in the form, such asfile[title]
,file[description]
, etc. - Error Handling: It is recommended to include error handling to manage any issues that arise during data processing.
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.
Form Attributes:
action="/set-images"
: Specifies the endpoint to which the form data will be submitted.method="post"
: Indicates that the form data will be sent using the POST method.enctype="multipart/form-data"
: Sets the encoding type tomultipart/form-data
, which is required for file uploads.
Form Elements:
<input type="file" name="files" multiple />
: Provides a file input field allowing users to select multiple files. Thename="files"
attribute is used to identify the file input in the form submission.<button type="submit">Upload</button>
: A button that submits the form data 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.
Route Definition: The
app.post("/set-images", ...)
method defines a route to process POST requests at the/set-images
URL.Data Handling:
const { files } = data
: Extracts thefiles
object from the request data. This object contains the uploaded files.- File Processing:
- Loop: Iterates through each file in the
files
array. - File Path: Constructs the path where each file will be saved (e.g.,
images/${file.filename}
). await writeFile(filePath, file.body)
: Asynchronously writes each file’s content to the specified path using thewriteFile
function.
- Loop: Iterates through each file in the
Response Handling:
- Success: On successful file upload, the server redirects the client to
/set/images
. - Error Handling: If an error occurs during file processing, it logs the error and responds with a 500 status code and a generic error message.
- Success: On successful file upload, the server redirects the client to
Request Size Limit: The request size is limited to 5 MB to prevent excessively large file uploads.
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:
headers
: Contains metadata about the file, such as content type and other HTTP headers.body
: The actual binary content of the file.filename
: The original name of the file as provided by the client.contentType
: The MIME type of the file, indicating its format.
For more details about the meros
library, you can visit its npm page.
Content
- Sending a JSON Response
- Handling POST Requests
- JSON
- URL-encoded form data
- multipart/form-data