« Previous Tutorial Next Tutorial »

This is a bit of a cleanup episode. We’re going to switch app.js over to ES7, just for consistency since we’ll be writing everything else using new language features. Then we’re going to install Nodemon, and then we’re going to set up our API directory in our routes folder. Let’s get to it.

First part’s easy. We’re going to go through and change our vars to const and let … actually, entirely const in this case. Let’s do that. I like to just multi-select in Sublime by selecting the first instance of var; and then using cmd-or-ctrl-D. Then you just type const once, and every instance you've selected changes to const. Now, you may be wondering why line 28 is a const even though we’re adding something to the object on line 29. The reason for this is because const objects are only immutable—which means they can’t be changed—at the top level. For example, you can’t say:

const user = {
   name: 'Joe Smith',
   age: 24

and then do this later in the code:

user = {
  name: 'Ted Smith',
  age: 36

You'll get an error, because that’s replacing the entire object with a brand new object. You can change the properties, though, so you could do:

user.name = 'Ted Smith';
user.age = '36';

And it'd work. I know it seems like it's splitting hairs if you can replace an object's entire set of properties, but as far as JavaScript is concerned, it's a very different process.

A quick side-note about const and let … they have different scope than var, and there are occasions where we will still want to use var. For example, this code:

var userCount = 650;
if (user.isNew() === true) {
  var userCount = 651;

wouldn't work because var's scope falls through into the if block, so you'd get an error about assigning the variable twice. This code would work:

let userCount = 650;
if (user.isNew() === true) {
  let userCount = 651;

However it's important to understand that despite having the same name, those are two different variables. Outside of that if block, if you console.log userCount, you'd get 650. Inside it, you'd get 651. This is important to understand, and also hammers home why you'd want to be careful with variable names, because things can get confusing.

All right, let's convert the two functions in this file to arrow functions. Again, we're not messing with the scope of this in these functions, so we don't have to convert them, but my feeling is that in general the best way to learn this stuff is to see it a lot and work with it a lot. Helps drill it into your brain. Or at least, that's what works for me.

So convert line 27 to:

app.use((req, res, next) => {

and line 34 to:

app.use((err, req, res, next) => {

All right, we're good here. Save the file, switch to your terminal or command prompt, and kill your server. We're going to install a terrific program called Nodemon that will make it so we don't have to manually restart our server every time we make a change to our JavaScript and want to see it reflected on the site. To do this we type:

yarn global add nodemon

Hit enter and watch it go. Hooray! We'll eventually want to set Nodemon up to ignore some files (we don't need it restarting our node server every time we change client-side JS, for example), but we'll deal with that later. For now just type:

nodemon yarn start

to launch our server again. Now let's make a quick change to /routes/index.js just to see things in action. Change the title on line six from "MusicList" to "MusicList Alpha" and save. If we check our terminal, we can see that Nodemon caught the change and automatically restarted our server. Now refresh localhost:3000 and note our title has changed without having to refresh the server. That's it … that's the good stuff!

All right, let's configure our API directory. This doesn't really involve much up front. We're doing it here more to show how to add a route in Express than because it's a necessary step. So, first off, make an api folder as a subdirectory of your routes directory. There's about a hundred ways to do this. I'm just going to use Sublime. Then I'm going to make a new file in /api called index.js. In this file, we'll want to start with three lines that will be in all of our route files:

const express = require('express');
const router = express.Router();

module.exports = router;

Again, those first two lines initialize the route. The final line exports it for use in our app, and it's good practice to make sure that these are always the first and last lines of the file, no matter what comes between them. You could theoretically put function declarations underneath the exports line, since JavaScript parses them first regardless of order (which is why you can use functions defined at the bottom of a file in code at the top), but I still prefer to make sure the export line is the last thing in the file.

OK, let's make this route do something and then hook our app up to it. Between those lines, write the following code:

router.get('/', (req, res, next) => {
  res.json({ text: 'MusicList API Test' });

This is just sending a basic JSON test response. Let's make it work. Open app.js and find line 8:

const index = require('./routes/index');

Below that, add this line:

const api = require('./routes/api/index');

Then find line 25:

app.use('/', index);

And below it, add this line:

app.use('/api', api);

Save the file and we're done. Our API is connected to the app and ready for testing. Of course, we've only built a single HTTP GET response, but that's fine for now. We'll also want to eventually lock the API down so its only accessible by MusicList, and not the general public, but that's another tutorial. For now, let's go check out API response by navigating to localhost:3000/api

There we go. Our API is sending JSON. We'll be building more routes and responses shortly, but that's all for this tutorial. See you next time!

« Previous Tutorial Next Tutorial »