Express JSON receiving parsing and sending
In express json can be sent from the server to a client with response methods like res.json, it can also be received from clients by making post requests from a client system, and then parsing the incoming body with the body parser middleware. In late versions of express such as 4.17+ there is now an express.json method that can be used as a kind of short hand for the body parser middleware to quickly parse a json body of an incoming post request.
In this post I will be coving some basics and more about expressjs and json when it comes to both sending it and receiving it to and from a client system.
1 - Express JSON - Sending JSON from expressjs
To send JSON from a server side script with expressjs just use the json response method, by just calling the method and passing the object that you want sent as JSON as the first argument.
Sending JSON from a server to a client is simple and straight forward when using the express JSON response method to do so. The reason why is that the express JSON response method is a convenience method that sets the proper content type response header, and uses the JSON.stringify the object for you.
1.1 - Sending JSON the hard way
To gain a deeper understating and appreciation for the res.json response method take into account the following example that does the same thing as the above one.
Express has a few methods like this that help make code cleaner, sometimes they might not always be the best choice though. If for some reason you want to have control over the Content-Type header you would have to do something like this.
2 - Express JSON - Receiving from a client parsing and sending
So in this example I just have a basic client system that just sends a post request, and then the body parser middleware is then used to parse the body of that request into a workable object via the req.body property of a request object. The incoming payload can then be used.
4 - Conclusion