Express post request example
The app.post method can be used in express.js to define what is to be done in the event that a post request is received from a client system. Working with express post requests can be a somewhat complicated process, there is much to cover in terms of how to go about making a client system that will send post requests, and also how to parse the incoming request as well. I will not be going into every little detail about this in this post of course, but I will be covering some basic examples, and link to other relevant works when it comes to how to get up and running with express post requests.
1 - Express post example using just a static html file in a public folder
So in this example I am just using express.js on top of node.js, and when it comes to rendering I am just using plain old static html files. In addition I am using the browser native XMLHttpRequest as a way to make the post request rather than using something like axios. I am slo using the express.js built in body parser midddleware as well to parse the incoming post request.
1.1 - The public/static.html file
This html file will serve as an index of sorts for the backend code that I will get to latter in this section.
1.2 - The public/static_client.js file
I will not be getting into every little detail here when it comes to making post requests with XMLHTTPRequest, but one of the most important things to be aware of here is the request header that I am setting. In this example I am using JSON as a way to transmit data from a client system back to the back end system. The body parser that I am using in express will only work as expected if the proper headers are sent along with the request.
1.3 - The app_static.js file
Once that is done I am the use the app.post to set up what to do for a express post request. The body parser middleware will parse the incoming request and populate the req.body property. There I will have access to what has been sent from the client. In this simple example I am using that to just simply figure the power of the base and pow properties sent fro the client, and then send that result back to the client in the form of a string.
2 - Conclusion
So the app.post method is one of many app object methods in express that are key to the process of defining application level middleware in express. For more on app object methods be sure to check out my post on the app object in express, there is also my main post on express in general as well.