Moving Server Requests to Front End Via API
Daily Standup
July 27, 2019
Still working away at project GFT. Most recently I updated some code to move some backend logic into the front end.
I have some buttons on the site which manage some pretty important functionality. Until now, when you press the button, a form is submitted to the server and the page needed to reload in order for the action to be carried out. I wanted to carry out the action without reloading the page.
To do this, I needed to essentially add an API to the backend of my app, and then write event handlers to make HTTP requests in the front end.
Adding an API
Writing an API (or rather, avoiding doing so) was the reason I used forms in the first place. But I guess for some things it really can’t be avoided.
Thankfully, the logic for an API endpoint is pretty much the same as the code for handling the form submission, only instead of responding with a new page, I send some JSON back as the response, which the frontend event listeners handle:
// Controller for server handling |
!! Big Important Step !!
At this stage my app is already using body-parser
to parse form data on the body object. But that’s not enough once we start working with JSON being sent over HTTP requests! In the main server file (app.js
in my case), another line must be added:
app.use(bodyParser.json()); // ADD THIS!! |
It took me a while to figure out why nothing was coming through on the request body…save yourself the trouble 😂
And voila!
Up Next
Now that it’s working I think I need to add some kind of indication that ‘something’ is happening when you press the button. Most of the time the response is pretty quick, but if it takes the server a bit longer to carry out the action and respond, it looks like you’ve clicked the button and nothing happens. So I will add some kind of progress or waiting animation to make this clearer for the user.