8000 GitHub - Lete114/Body-Data: A lightweight Node.js utility to extract query parameters and request body data from `IncomingMessage`. Supports common `Content-Type` formats and safe fallbacks.
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

A lightweight Node.js utility to extract query parameters and request body data from `IncomingMessage`. Supports common `Content-Type` formats and safe fallbacks.

License

Notifications You must be signed in to change notification settings

Lete114/Body-Data

Repository files navigation

πŸ“¦ body-data

visitors npm version npm downloads bundle JSDocs License

A lightweight Node.js utility to extract query parameters and request body data from IncomingMessage. Supports common Content-Type formats and safe fallbacks.

✨ Features

  • βœ… Extract query parameters from GET requests
  • βœ… Parse request body from POST requests
  • βœ… Supports application/json, x-www-form-urlencoded, text/plain, multipart/form-data, and others
  • βœ… Safe fallback parsing
  • βœ… Zero dependencies
  • βœ… Configurable parsing options: encoding, content-type override, raw mode, and custom error handling

πŸ“¦ Installation

npm install body-data
# or
pnpm add body-data

πŸš€ Usage Examples

1. Using bodyData

bodyData is a high-level utility that returns both params (query) and body data.

import http from 'node:http'
import { bodyData } from 'body-data'

http.createServer(async (req, res) => {
  const data = await bodyData(req)

  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify(data))
}).listen(3000)

Request Example:

curl "http://localhost:3000?name=lete&age=18" \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"gender":"male"}'

Response:

{
  "params": {
    "name": "lete",
    "age": "18"
  },
  "body": {
    "gender": "male"
  }
}

2. Using getParams

Use getParams to only extract query parameters from the URL.

import http from 'node:http'
import { getParams } from 'body-data'

http.createServer((req, res) => {
  const params = getParams(req)

  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ params }))
}).listen(3000)

Request Example:

A348
curl "http://localhost:3000?foo=bar&count=10"

Response:

{
  "params": {
    "foo": "bar",
    "count": "10"
  }
}

3. Using getBody

Use getBody to only extract the body from a POST request.

import http from 'node:http'
import { getBody } from 'body-data'

http.createServer(async (req, res) => {
  const body = await getBody(req)

  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ body }))
}).listen(3000)

Request Example:

curl "http://localhost:3000" \
  -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=test&password=1234"

Response:

{
  "body": {
    "username": "test",
    "password": "1234"
  }
}

πŸ“– API Reference

bodyData(req: IncomingMessage): Promise<{ params, body }>

Returns an object with:

  • params: Query parameters (from URL)
  • body: Parsed request body

getParams(req: IncomingMessage): Record<string, any>

Parses the query string from the request URL.

getBody(req: IncomingMessage): Promise<Record<string, any>>

Parses the body of the request based on Content-Type. Supports:

  • application/json
  • application/x-www-form-urlencoded
  • text/plain
  • multipart/form-data (returns raw string)
  • Fallback: returns { raw: string }

Options (IBodyOptions):

Option Type Description
raw boolean Return raw body string instead of parsing. Default: false
encoding BufferEncoding Text encoding for reading the body. Default: 'utf-8'
contentType string Force a specific Content-Type (overrides request headers)
backContentType string Fallback Content-Type when none is provided
onError (err: Error) => void Custom error handler for parse or stream errors

βœ… Example with Custom Options

const body = await getBody(req, {
  raw: false,
  encoding: 'utf-8',
  contentType: 'application/json',
  backContentType: 'text/plain',
  onError: err => console.error('Body parse error:', err),
})

πŸ§ͺ Testing

pnpm test

πŸ“„ License

MIT License Β© Lete114

About

A lightweight Node.js utility to extract query parameters and request body data from `IncomingMessage`. Supports common `Content-Type` formats and safe fallbacks.

Topics

Resources

License

Stars

Watchers

Forks

0