• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Body parsing

body build status

Body parsing

Originally taken from npm-www

Example

var textBody = require("body")
var jsonBody = require("body/json")
var formBody = require("body/form")
var anyBody = require("body/any")
var http = require("http")
var sendJson = require("send-data/json")

http.createServer(function handleRequest(req, res) {
    function send(err, body) {
        sendJson(req, res, body)
    }

    if (req.url === "/body") {
        // all functions can be called with (req, cb)
        textBody(req, send)
    } else if (req.url === "/form") {
        // all functions can be called with (req, opts, cb)
        formBody(req, {}, send)
    } else if (req.url === "/json") {
        // all functions can be called with (req, res, cb)
        jsonBody(req, res, send)
    } else if (req.url === "/any") {
        // all functions can be called with (req, res, opts, cb)
        anyBody(req, res, {}, send)
    }
})

body simply parses the request body and returns it in the callback. jsonBody and formBody call JSON.parse and querystring.parse respectively on the body.

anyBody will detect the content-type of the request and use the appropiate body method.

Example generators

You can use body with generators as the body functions will return a continuable if you don't pass a callback.

var http = require("http")
var Router = require("routes-router")
var jsonBody = require("body/json")
var formBody = require("body/form")
// async turns a generator into an async function taking a cb
var async = require("gens")

// the router works with normal async functions.
// router automatically handles errors as 500 responses
var app = Router({
    // do whatever you want. the jsonBody error would go here
    errorHandler: function (req, res, err) {
        res.statusCode = 500
        res.end(err.message)
    }
})

app.addRoute("/json", async(function* (req, res) {
    // if jsonBody has an error it just goes to the cb
    // in the called in the router. and it does the correct thing
    // it shows your 500 page.
    var body = yield jsonBody(req, res)

    res.setHeader("content-type", "application/json")
    res.end(JSON.stringify(body))
}))

app.addRoute("/form", async(function* (req, res) {
    var body = yield formBody(req, res)

    res.setHeader("content-type", "application/json")
    res.end(JSON.stringify(body))
}))

// app returned from the router is just a function(req, res) {}
// that dispatches the req/res to the correct route based on
// the routers routing table & req.url
http.createServer(app).listen(8080)

Documentation

textBody(req, res?, opts?, cb<Error, String>)

textBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        cache?: Boolean,
        encoding?: String
    },
    cb: Callback<err: Error, bodyPayload: String>
) => void

textBody allows you to get the body from any readable stream. It will read the entire content of the stream into memory and give it back to you in the callback.

  • limit: You can set opts.limit to a custom number to change the limit at which textBody gives up. By default it will only read a 1MB body, if a stream contains more then 1MB it returns an error. This prevents someone attacking your HTTP server with an infinite body causing an out of memory attack.
  • encoding: You can set encoding. All encodings that are valid on a Buffer are valid options. It defaults to 'utf8'
var textBody = require("body")
var http = require("http")

http.createServer(function (req, res) {
    textBody(req, res, function (err, body) {
        // err probably means invalid HTTP protocol or some shiz.
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.end(body)
    })
}).listen(8080)

formBody(req, res?, opts?, cb<Error, Any>)

formBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String,
        querystring: {
            parse: (String, Callback<Error, Any>) => void
        }
    },
    cb: Callback<err: Error, bodyPayload: Any>
) => void

formBody allows you to get the body of a readable stream. It does the same as textBody but assumes the content is querystring encoded and parses just like it was a <form> submit.

  • limit: same as textBody
  • encoding: same as textBody
  • querystring: You can pass a custom querystring parser if you want. It should have a parse method that takes a string and a callback. It should return the value in the callback or a parsing error
var formBody = require("body/form")
var http = require("http")

http.createServer(function (req, res) {
    formBody(req, res, function (err, body) {
        // err probably means invalid HTTP protocol or some shiz.
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.setHeader("content-type", "application/json")
        res.end(JSON.stringify(body))
    })
}).listen(8080)

jsonBody(req, res?, opts?, cb<Error, Any>)

jsonBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String,
        reviver?: (Any) => Any
        JSON?: {
            parse: (String, reviver?: Function, Callback<Error, Any>) => void
        }
    },
    cb: Callback<err: Error, bodyPayload: Any>
) => void

jsonBody allows you to get the body of a readable stream. It does the same as textbody but assumes the content it a JSON value and parses it using JSON.parse. If JSON.parse throws an exception then it calls the callback with the exception.

  • limit: same as textBody
  • encoding: same as textBody
  • reviver: A reviver function that will be passed to JSON.parse as the second argument
  • JSON: You can pass a custom JSON parser if you want. It should have a parse method that takes a string, an optional reviver and a callback. It should return the value in the callback or a parsing error.
var jsonBody = require("body/json")
var http = require("http")

http.createServer(function (req, res) {
    jsonBody(req, res, function (err, body) {
        // err is probably an invalid json error
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.setHeader("content-type", "application/json")
        res.end(JSON.stringify(body))
    })
}).listen(8080)

anyBody(req, res?, opts?, cb<Error, Any>)

anyBody := (
    req: HttpRequest,
    res?: HttpResponse,
    opts?: {
        limit?: Number,
        encoding?: String,
        reviver?: (Any) => Any
        JSON?: {
            parse: (String, reviver?: Function, Callback<Error, Any>) => void
        },
        querystring: {
            parse: (String, Callback<Error, Any>) => void
        }
    },
    cb: Callback<err: Error, bodyPayload: Any>
) => void

anyBody allows you to get the body of a HTTPRequest. It does the same as textBody except it parses the content-type header and uses either the jsonBody or the formBody function.

This allows you to write POST route handlers that work with both ajax and html form submits.

  • limit: same as textBody
  • encoding: same as textBody
  • reviver: same as jsonBody
  • JSON: same as jsonBody
  • querystring: same as formBody
var anyBody = require("body/any")
var http = require("http")

http.createServer(function (req, res) {
    anyBody(req, res, function (err, body) {
        // err is probably an invalid json error
        if (err) {
            res.statusCode = 500
            return res.end("NO U")
        }

        // I am an echo server
        res.setHeader("content-type", "application/json")
        res.end(JSON.stringify(body))
    })
}).listen(8080)

Installation

npm install body

Tests

npm test

Contributors

  • Raynos

MIT Licenced

More Repositories

1

mercury

A truly modular frontend framework
JavaScript
2,818
star
2

http-framework

A web framework based purely on require('http')
JavaScript
523
star
3

xtend

extend like a boss
JavaScript
305
star
4

global

Require global variables
JavaScript
252
star
5

main-loop

A rendering loop for diffable UIs
JavaScript
172
star
6

leaked-handles

Detect any handles leaked in node
JavaScript
166
star
7

DOM-shim

Shims out the entire DOM4 API
JavaScript
155
star
8

function-bind

JavaScript
136
star
9

error

Error handling utilities for node
JavaScript
122
star
10

after

All the flow control you'll ever need
JavaScript
116
star
11

min-document

A minimal DOM implementation
JavaScript
109
star
12

jsig

From scratch type-checker
JavaScript
104
star
13

duplexer

Creates a duplex stream
JavaScript
95
star
14

observ

A observable value representation
JavaScript
74
star
15

observ-struct

An object with observable key value pairs
JavaScript
72
star
16

virtual-hyperscript

A DSL for creating virtual trees
JavaScript
59
star
17

topology

Different network topologies
JavaScript
57
star
18

dom-delegator

Decorate elements with delegated events
JavaScript
57
star
19

continuable

Idea for callbacks as values
JavaScript
54
star
20

live-reload

A live reload server & client
JavaScript
51
star
21

pd

Property Descriptors made easy
JavaScript
44
star
22

engine.io-stream

Wrap engine.io in a real stream interface
JavaScript
44
star
23

vdom-thunk

A thunk optimization for virtual-dom
JavaScript
42
star
24

stream-chat

Alpha chat app using streams for communication
JavaScript
40
star
25

resultify

Handle errors with async/await without try/catch.
JavaScript
38
star
26

graphics

Efficient data structures that represent renderable scenes
JavaScript
38
star
27

safe-json-parse

Parse JSON safely without throwing
JavaScript
36
star
28

webrtc-stream

WebRTC demo
JavaScript
34
star
29

level-livefeed

Live query a range in leveldb
JavaScript
34
star
30

http-works

A workshopper for http framework
JavaScript
32
star
31

tsdocstandard

Standard but also use TypeScript on JS files with jsdoc.
JavaScript
31
star
32

discovery-network

A peer to peer discovery network
JavaScript
31
star
33

geval

JavaScript
30
star
34

corsify

CORS up a route handler
JavaScript
29
star
35

itape

An interactive tape runner.
JavaScript
27
star
36

ncore

Core infrastructure for node.
JavaScript
26
star
37

send-data

send data through response
JavaScript
26
star
38

observ-array

An array containing observable values
JavaScript
26
star
39

append-only

Append only scuttlebutt structure
JavaScript
25
star
40

jsonml-stringify

Convert jsonml arrays to html strings
JavaScript
22
star
41

eslint-plugin-perf-standard

A set of custom plugins to enforce high performance JS
JavaScript
21
star
42

routes-router

Simplest request handler possible
JavaScript
21
star
43

for-each

A better forEach
JavaScript
21
star
44

auth-stream

Authorize access before exposing a stream
JavaScript
21
star
45

value-event

Create DOM event handlers that write to listeners
JavaScript
21
star
46

boot

Shoe & mux demux with reconnect!
JavaScript
20
star
47

stream-router

Easily route mdm streams
JavaScript
19
star
48

raynos-blog

My blog
JavaScript
19
star
49

jsconf2014-talk

Modular frontend with NPM & pals
JavaScript
19
star
50

whatwg-streams

JavaScript
17
star
51

deep-merge

Deep merge objects with custom merging logic
JavaScript
17
star
52

map-async

Asynchronously map over a list
JavaScript
17
star
53

data-channel

Turn a data channel into a stream
JavaScript
17
star
54

gens

Experimental usage of generators
JavaScript
17
star
55

level-cache

An in memory cache on top of leveldb
JavaScript
17
star
56

npm-bin-deps

NPR allows you to run your CLI dependencies without having a copy in node_modules.
JavaScript
16
star
57

serve-browserify

HTTP handler for serving browserify bundles
JavaScript
16
star
58

delta-stream

A stream that emits deltas in change
JavaScript
15
star
59

examplifier

Turn bland source code into interactive demos
JavaScript
15
star
60

distributed-map

A distributed key value store in the browser
JavaScript
14
star
61

clientmongo

Use the mongo API in the browser
JavaScript
14
star
62

multi-channel-mdm

Create persisted channels to broadcast data!
JavaScript
14
star
63

buffer-stream

A duplex stream that buffers writes
JavaScript
14
star
64

chain-stream

Chain stream operations together
JavaScript
14
star
65

fake-s3

a fake s3 server for testing purposes.
JavaScript
13
star
66

signal-channel

A signal channel that empowers webrtc
JavaScript
13
star
67

levelidb

A levelup interface on top of indexeddb
JavaScript
12
star
68

reduce

A better [].reduce
JavaScript
12
star
69

level-write-stream

A writeStream implementation for leveldb
JavaScript
12
star
70

frontend-framework

Building frontend apps with small modules
JavaScript
12
star
71

browserify-server

spin up browserify demos real easy
JavaScript
12
star
72

format-stack

Formats a stack with colors
JavaScript
12
star
73

feature

Feature detection for host objects
JavaScript
12
star
74

hash-router

A frontend router for the hash change event
JavaScript
11
star
75

promise-stream

A Promises/A implementation based on streams
JavaScript
11
star
76

html-delegator

Decorate elements with delegated events
JavaScript
11
star
77

ready-signal

A ready signal. Wait for ready and signal it's ready
JavaScript
11
star
78

ev-store

Stores event listeners and event handles on a DOM object
JavaScript
11
star
79

weakmap-shim

JavaScript
10
star
80

to-array

Turn an array like into an array
JavaScript
10
star
81

term-color

A lighter weight alternative to chalk
JavaScript
9
star
82

static-config

JavaScript
9
star
83

npm-less

JavaScript
9
star
84

eventemitter-light

It's a light event emitter
JavaScript
9
star
85

expiry-model

A scuttlebutt model that expires keys
JavaScript
9
star
86

http-methods

Handle multiple methods elegantly
JavaScript
9
star
87

mux-demux-shoe

Shoe and mux-demux come together!
JavaScript
9
star
88

validate-form

JavaScript
9
star
89

iterators

iterate over collections asynchronously
JavaScript
8
star
90

fake-sqs

Runs a fake SQS server on a HTTP port.
JavaScript
8
star
91

redirecter

JavaScript
8
star
92

seaport-proxy

Proxy all the seaports!
JavaScript
8
star
93

request-proxy

A version of request that's local to a fixed base uri
JavaScript
8
star
94

pre-bundled

A tool that pre bundles and re publishes npm dependencies
JavaScript
8
star
95

mongo-col

mongodb collection wrapper
JavaScript
8
star
96

tape-harness

A helper to run integration tests against an application
JavaScript
8
star
97

sockjs-stream

A streaming API for sockjs
JavaScript
7
star
98

add

Add two numbers
JavaScript
7
star
99

so642

JavaScript
7
star
100

composite

Compose functions together
JavaScript
7
star