Moving Server Requests to Front End Via API

Daily Standup

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
controllerName(req, res, next) {
read.oneGameByUserAndName(req.user.localId, req.body.list)
.then((game) => {
return game.doSomething(req.body.game_id)
.then(() => {
return res.status(200).redirect(req.headers.referer);
})
}).catch(err => {
console.log(`Error name: ${err}`);
res.status(400).redirect(req.headers.referer);
})
},

// Controller for sending API response
controllerName(req, res, next) {
read.oneGameByUserAndName(req.user.localId, req.body.list)
.then((game) => {
return game.doSomething(req.body.game_id)
.then(() => {
return res.status(201).send({
success: true,
});
})
}).catch(err => {
console.log(`Error name: ${err}`);
res.status(400).send({
success: false,
});
})
},

!! 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!!
app.use(bodyParser.urlencoded({ extended: true }));

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.