This course will be retired on February 24, 2020. We recommend "Build a REST API With Express" for up-to-date content.
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
We are going to move the API logic to keep our application clutter-free. We'll be using Node’s module system to access our controller without our routes.
Here's how to get the code to follow along with this video:
git clone https://github.com/treehouse-projects/mean-todo.git cd mean-todo git checkout tags/s2v2 -b create-an-api-controller npm install
Our application is coming along nicely.
We could continue writing code in our app.js file, but
writing code in a single file is hard to maintain as a project grows.
Let's move our API router to its own file.
First, let's create a new directory called api.
This is where we're going to store all of our API routes.
Now let's create a file called index.js.
This file's going to act as our API module.
The top of the file I'll add the use strict statement to
make sure that node runs our file with a strict interpretation.
We'll also include our dependency express.
Now let's rip our router code out of our app.js file.
We'll move that here.
And keep in mind that we left this line here in,
because we're going to use it when we import our router in just a moment.
Now before this code works as an imported module, we'll need to export our router.
You're already familiar with importing third-party modules,
just like you did up here with express.
So this isn't going to work much differently.
The only real difference here is that we'll be referencing files
from the file system, so we'll need to pay close attention to our file path names.
As usual, if you have questions when we're done, you can reference the teacher's
notes for more information on Node's module loading system.
Now the thing we want to expose is the router itself.
So we'll use Node's module.exports method, and we'll set that equal to the router.
Now when we go back to our app.js file, we can say that our router,
Is the API module that we've required.
And of course, we're mounting the router to the API URL.
Let's start our server, and make sure this works.
Great, there's our API todos, but we now have a much more modular application.
Great work so far.
Our API is starting to come together nicely.
Next, we'll add some mock data to our todos route.
You need to sign up for Treehouse in order to download course files.Sign up