Express’s json() and urlencoded() Explained
Express is a Node.js framework best known by beginners for simplifying syntax in building basic back-end servers. Express.js comes with a lot of built in modules and functions, and we’re going to talk about two of them specifically today: .json() and .urlencoded().
.json() and .urlencoded() are express middleware functions that parse data in outgoing requests. Let’s break that down:
Nội Dung Chính
1.) They are middleware functions
So what is middleware?
Middleware is a function or piece of code that is called (run) between when a server gets a request from a client and when it sends a response back to the client. Middleware can take many forms, like simple logs:
console.log('server listening on port ${port})
Enter fullscreen mode
Exit fullscreen mode
or functions that manipulate incoming or outgoing data (such as .json()
and .urlencoded()
)
2.) They parse outgoing requsts
Both are used to parse data that goes out on the req
object. Usage of .json() and .urlencoded() depends on the encoding of data you are sending in your server request.
Because they are used on the req
side of a server call, you only need them for POST and PUT requests, or any outgoing request that carries data. They aren’t needed for GET or DELETE requests.
Incidently, both used to be part of body-parser
which was in itself a piece of middleware that was taken out and separated from Express, but since Express 4.16.0 they’re back into Express and use the express.FUNCTIONNAME()
syntax.
So what exactly is the difference and how can I use them?
Express.json() expects request data to be sent in JSON format, which often resembles a simple JS object:
{"Name": "Pikachu", "Type": "Banana", "Number In Stable": 12}
Enter fullscreen mode
Exit fullscreen mode
Express.urlencoded() expects request data to be sent encoded in the URL, usually in strings or arrays:
.../Name=Pikachu&Type=Banana&Number+In+Stable=12
Enter fullscreen mode
Exit fullscreen mode
You can call them using
express.json()
or
express.urlencoded()
Enter fullscreen mode
Exit fullscreen mode
but if you want them to be used every time a request is made on the server (which is a typical use case), you can also use app.use
:
app.use(express.json())
or
app.use(express.urlencoded())
Enter fullscreen mode
Exit fullscreen mode
Summary
express.json()
and express.urlencoded()
are helpful express middleware parser functions that let you parse outgoing request data depending on the encoding of data you’re sending to the server.