FCC Speedrun — Request Header Microservice

P1xt
P1xt’s Blog
Published in
2 min readMar 10, 2017

Continuing through the FCC Backend projects in order to finish the Chingu FCC Speedrun Challenge speed run, next I came to the Request Header Microservice API project.

Ok, I’ll be honest here — I reused next to everything from my Timestamp Microservice project. Almost all the baseline setup is exactly the same: Setup a Node.js/Express app, setup routing, create an index view in pug. The only real difference is that the API request had to give me some information my browser knows about my environment instead of, you know, manipulating some timestamps.

Step 1 — look at what’s in the request headers

The absolute first thing I did was rename my api module, then pop right into it and instead of having it return what the project expects, I had it return everything in the request headers.

res.send(req.headers);

Step 2 — yank the data you need out of the request headers

This let me take a look at everything that was available to me in the request headers then bim, bam, boom, I just parsed out those bits and I was done!

My final module that handles literally everything needed for the “real work” on this project was:

module.exports = {
parse: function (req, res) {
let requestData = {
"ipaddress": req.headers['x-forwarded-for'].split(',')[0] ||
req.connection.remoteAddress.split(',')[0],
"language": req.headers['accept-language'].split(',')[0],
"software": req.headers['user-agent'].split(') ')[0].split(' (')[1]
}
res.send(requestData);
}
}

Mostly it was just a matter of splitting some fields available in the request headers on a comma, then returning everything that came before the first comma (which ends up being in index zero after the split). Getting my operating system out of user-agent was a bit more complex because it wasn’t a simple split on a comma, I had to find the string between the first braces.

Don’t let this one scare you, just print out the request headers then get to work splitting them apart into the values you need for the JSON you’re returning.

Notes:

My progress in the Speedrun thusfar:

--

--