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
There is sending JSON from a server to a client as a response to a request from that client, and then there is sending JSON from a client system to a server as a payload by way of a POST request. There are a number of ways to send a post request from a client system to express when it comes to what is available in terms of front end frameworks. However when it comes to plain native javaScript the tired yet true way of sending one is to use XMLHttpRequest.
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
So then there are the basics of working with json in an expressjs project, the process of doing so is fairly easy. However the next step is working out all the code that will run on the client system, and coming up with standards when it comes to how to go about formating objects that will be sent back and forth. However all of that is what one needs to get a grasp on when it comes to making a real project with express and nodejs, and this is just a simple post on just working with JavaScript Object Notation.