Post requests are an important aspect of any kind of full stack application. You have some data on the client, and you need to shoot it over to the back end system. Doing so in hapi is pretty easy, in this post I will be covering a very basic approach that does not even require any kind of client system, apart from just a simple postIt function that will be copied into the console.
It will likely be a simple method written in vanilla js, because at the earliest stages of development I may not have even decided if I am going to use jquery, or some other deal on the client side. In addition I will want to custom tailer some of the default values of the method so that it works very quickly with just one argument, but can also be used to post in just about any kind of fashion.
As such that method might look something like this.
Yes I made the data argument the first argument, so that if I do not need to do anything special I can just do this:
In addition I made it so data can be whatever it is that I pass to postIt, in many cases I may need to stringify something into JSON, but maybe not always, so I leave that up to how I use it.
If need be I can change the url, do something with the xhr object before it is sent, such as adding a header, and add custom done and fail callbacks. Still out of the box I can just chuck something at the server with just one argument, and I like that.
Now that I have my simple vanilla js tool for making post requests, it is time to get together the basic back end system to get started with post requests using hapi.
This is the most basic form I can think of when it comes to getting started with post requests in hapi, as such when it is saved as post.js, and started the script in the console with like so :
When I go to http://localhost:3000 in the browser I will get an error message, because I have not set any get handler for the root name space yet.
After doing so I receive the response object in the console, and the expected response ‘Yes this is Mr Horse.’ is in the response, and responseText properties of the response object.
I am really liking hapi, it may prove to be a great alternative to express. I will be writing a few more posts on hapi for sure, so I have made it another one of my collections.