restful-api-node-express-4-router
Javascript

Build a RESTful API Using Node and Express 4

With the release of Express 4.0 just a few days ago, lots of our Node apps will have some changes in how they handle routing. With the changes in the Express Router, we have more flexibility in how we can define the routes for our applications.

Today we’ll be looking at creating a RESTful API using Node, Express 4 and its Router, and Mongoose to interact with a MongoDB instance. We will also be testing our API using Postman in Chrome.

Let’s look at the API we want to build and what it can do.

Our Application

We are going to build an API that will:

  • Handle CRUD for an item (we’re going to use bears)
  • Have a standard URL (http://example.com/api/bears and http://example.com/api/bears/:bear_id)
  • Use the proper HTTP verbs to make it RESTful (GET, POST, PUT, and DELETE)
  • Return JSON data
  • Log all requests to the console

All of this is pretty standard for RESTful APIs. Feel free to switch out bears for anything that you will want to build for your application (users, superheroes, beers, etc).

Make sure you have Node installed and let’s get to it!

Getting Started

Let’s look at all the files we will need to create our API. We will need to define our Node packages, start our server using Express, define our model, declare our routes using Express, and last but not least, test our API.

Here is our file structure. We won’t need many files and we’ll keep this very simple for demonstration purposes. When moving to a production or larger application, you’ll want to separate things out into a good structure (like having your routes in their own file).


	- app/
	----- models/
	---------- bear.js 	// our bear model
	- node_modules/     // created by npm. holds our dependencies/packages
	- package.json 		// define all our node app and dependencies
	- server.js 		// configure our application and create routes

Defining our Node Packages package.json

As with all of our Node projects, we will define the packages we need in package.json. Go ahead and create that file with these packages.

// package.json

{
	"name": "node-api",
	"main": "server.js",
	"dependencies": {
		"express": "~4.0.0",
		"mongoose": "~3.6.13",
		"body-parser": "~1.0.1"
	}
}

What do these packages do? express is the Node framework. mongoose is the ORM we will use to communicate with our MongoDB database. body-parser will let us pull POST content from our HTTP request so that we can do things like create a bear.

Installing Our Node Packages

This might be the easiest step. Go into the command line in the root of your application and type:


$ npm install

npm will now pull in all the packages defined into a node_modules folder in our project.

npm is Node’s package manager that will bring in all the packages we defined in package.json. Simple and easy. Now that we have our packages, let’s go ahead and use them when we set up our API.

We’ll be looking to our server.js file to setup our app since that’s the main file we declared in package.json.

Setting Up Our Server server.js

Node will look here when starting the application so that it will know how we want to configure our application and API.

We will start with the bear (get it?) essentials necessary to start up our application. We’ll keep this code clean and commented well so we understand exactly what’s going on every step of the way.

// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express'); 		// call express
var app        = express(); 				// define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser());

var port = process.env.PORT || 8080; 		// set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); 				// get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
	res.json({ message: 'hooray! welcome to our api!' });	
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

Wow we did a lot there! It’s all very simple though so let’s walk through it a bit.

Base Setup In our base setup, we pull in all the packages we pulled in using npm. We’ll grab express, define our app, get bodyParser and configure our app to use it. We can also set the port for our application.

Routes for Our API This section will hold all of our routes. The structure for using the Express Router let’s us pull in an instance of the router. We can then define routes and then apply those routes to a root URL (in this case, API).

Start our Server We’ll have our express app listen to the port we defined earlier. Then our application will be live and we can test it!

Starting Our Server and Testing

Let’s make sure that everything is working up to this point. We will start our Node app and then send a request to the one route we defined to make sure we get a response.

Let’s start our server. From the command line, type:


$ node server.js

You should see your Node app start up and Express will create a server.

node-api-start-server

Now that we know our application is up and running, let’s test it.

Testing Our API Using Postman

Postman will help us test our API. It will basically send HTTP requests to a URL of our choosing. We can even pass in parameters (which we will soon) and authentication (which we won’t need for this tutorial).

Open up Postman and let’s walk through how to use it.

postman-rest-client-node-api

All you have to do is enter your request URL, select an HTTP verb, and click Send. Simple enough right?

Here’s the moment we’ve been waiting for. Does our application work the way we configured it? Enter http://localhost:8080/api into the URL. GET is what we want since we just want to get data. Now click Send.

node-api-postman-test

Sweet! We got back exactly what we wanted. Now we know we can serve information to requests. Let’s wire up our database so we can start performing CRUD operations on some bears.

Database and Bear Model

We’ll keep this short and sweet so that we can get to the fun part of building the API routes. All we need to do is create a MongoDB database and have our application connect to it. We will also need to create a bear mongoose model so we can use mongoose to interact with our database.

Creating Our Database and Connecting

We will be using a database provided by Modulus. You can definitely create your own database and use it locally or use the awesome Mongolab. All you really need is a URI like below so that your application can connect.

Once you have your database created and have the URI to connect to, let’s add it to our application. In server.js in the Base Setup section, let’s add these two lines.

// server.js

// BASE SETUP
// =============================================================================

...

var mongoose   = require('mongoose');
mongoose.connect('mongodb://node:node@novus.modulusmongo.net:27017/Iganiq8o'); // connect to our database

...


That will grab the mongoose package and connect to our remote database hosted by Modulus. Now that we are connected to our database, let’s create a mongoose model to handle our bears.

Bear Model app/models/bear.js

Since the model won’t be the focus of this tutorial, we’ll just create a model and provide our bears with a name field. That’s it. Let’s create that file and define the model.

// app/models/bear.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var BearSchema   = new Schema({
	name: String
});

module.exports = mongoose.model('Bear', BearSchema);

With that file created, let’s pull it into our server.js so that we can use it within our application. We’ll add one more line to that file.

// server.js

// BASE SETUP
// =============================================================================

...

var Bear     = require('./app/models/bear');

...

Now our entire application is ready and wired up so we can start building out our routes. These routes will define our API and the main reason why this tutorial exists. Moving on!

Express Router and Routes

We will use an instance of the Express Router to handle all of our routes. Here is an overview of the routes we will require, what they will do, and the HTTP Verb used to access it.

Route HTTP Verb Description
/api/bears GET Get all the bears.
/api/bears POST Create a bear.
/api/bears/:bear_id GET Get a single bear.
/api/bears/:bear_id PUT Update a bear with new info.
/api/bears/:bear_id DELETE Delete a bear.

This will cover the basic routes needed for an API. This also keeps to a good format where we have kept the actions we need to execute (GET, POST, PUT, and DELETE) as HTTP verbs.

Route Middleware

We’ve already defined our first route and seen it in action. The Express Router gives us a great deal of flexibility in definining our routes.

Let’s say that we wanted something to happen every time a request was sent to our API. For this example we are just going to console.log() a message. Let’s add that middleware now.

// server.js

...

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); 				// get an instance of the express Router

// middleware to use for all requests
router.use(function(req, res, next) {
	// do logging
	console.log('Something is happening.');
	next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
	res.json({ message: 'hooray! welcome to our api!' });	
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

All we needed to do to declare that middleware was to use router.use(function()). The order of how we define the parts of our router is very important. They will run in the order that they are listed and thanks to the changes in Express 4.0, we won’t have problems doing this like in Express 3.0. Everything will run in the correct order.

We are sending back information as JSON data. This is standard for an API and will help the people using our API to use our data.

We will also add next() to indicate to our application that it should continue to the other routes. This is important because our application would stop at this middleware without it.

Middleware Uses Using middleware like this can be very powerful. We can do validations to make sure that everything coming from a request is safe and sound. We can throw errors here in case something is wrong. We can do some extra logging for analytics or any statistics we’d like to keep. There are many possibilities here. Go wild.

Testing Our Middleware

Now when we send a request to our application using Postman, Something is happening will be logged to our Node console (the command line).

node-api-route-middleware-express

With middleware, we can do awesome things to requests coming into our API. We will probably want to make sure that the user is authenticated to access our API. We’ll go over that in a future article, but for now let’s just log something to the console with our middleware.

Creating the Basic Routes

We will now create the routes to handle getting all the bears and creating a bear. This will both be handled using the /api/bears route. We’ll look at creating a bear first so that we have bears to work with.

Creating a Bear POST /api/bears

We will add the new route to handle POST and then test it using Postman.

// server.js

...

// ROUTES FOR OUR API
// =============================================================================

... // <-- route middleware and first route are here

// more routes for our API will happen here

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')

	// create a bear (accessed at POST http://localhost:8080/api/bears)
	.post(function(req, res) {
		
		var bear = new Bear(); 		// create a new instance of the Bear model
		bear.name = req.body.name;  // set the bears name (comes from the request)

		// save the bear and check for errors
		bear.save(function(err) {
			if (err)
				res.send(err);

			res.json({ message: 'Bear created!' });
		});
		
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

Now we have created the POST route for our application. We will use Express’s router.route() to handle multiple routes for the same URI. We are able to handle all the requests that end in /bears.

Let’s look at Postman now to create our bear.

node-api-postman-post-create-bear

Notice that we are sending the name data as x-www-form-urlencoded. This will send all of our data to the Node server as query strings.

We get back a successful message that our bear has been created. Let’s handle the API route to get all the bears so that we can see the bear that just came into existence.

Getting All Bears GET /api/bears

This will be a simple route that we will add onto the router.route() we created for the POST. With router.route(), we are able to chain together the different routes. This keeps our application clean and organized.

// server.js

...

// ROUTES FOR OUR API
// =============================================================================

... // <-- route middleware and first route are here

// more routes for our API will happen here

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')

	// create a bear (accessed at POST http://localhost:8080/api/bears)
	.post(function(req, res) {
		
		...
		
	})

	// get all the bears (accessed at GET http://localhost:8080/api/bears)
	.get(function(req, res) {
		Bear.find(function(err, bears) {
			if (err)
				res.send(err);

			res.json(bears);
		});
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

Straightforward route. Just send a GET request to http://localhost:8080/api/bears and we’ll get all the bears back in JSON format.

node-api-postman-get-all

Creating Routes for A Single Item

We’ve handled the group for routes ending in /bears. Let’s now handle the routes for when we pass in a parameter like a bear’s id.

The things we’ll want to do for this route, which will end in /bears/:bear_id will be:

  • Get a single bear.
  • Update a bear’s info.
  • Delete a bear.

The :bear_id from the request will be accessed thanks to that body-parser package we called earlier.

Getting a Single Bear GET /api/bears/:bear_id

We’ll add another router.route() to handle all requests that have a :bear_id attached to them.

// server.js

...

// ROUTES FOR OUR API
// =============================================================================

...

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
	...

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

	// get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
	.get(function(req, res) {
		Bear.findById(req.params.bear_id, function(err, bear) {
			if (err)
				res.send(err);
			res.json(bear);
		});
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

From our call to get all the bears, we can see the long id of one of our bears. Let’s grab that id and test getting that single bear in Postman.

node-api-postman-get-single

We can grab one bear from our API now! Let’s look at updating that bear’s name. Let’s say he wants to be more sophisiticated so we’ll rename him from Klaus to Sir Klaus.

Updating a Bear’s Info PUT /api/bears/:bear_id

Let’s chain a route onto our this router.route() and add a .put().

// server.js

...

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
	...

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

	// get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
	.get(function(req, res) {
		...
	})

	// update the bear with this id (accessed at PUT http://localhost:8080/api/bears/:bear_id)
	.put(function(req, res) {

		// use our bear model to find the bear we want
		Bear.findById(req.params.bear_id, function(err, bear) {

			if (err)
				res.send(err);

			bear.name = req.body.name; 	// update the bears info

			// save the bear
			bear.save(function(err) {
				if (err)
					res.send(err);

				res.json({ message: 'Bear updated!' });
			});

		});
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

We will use the given id from the PUT request, grab that bear, make changes, and save him back to the database.

node-api-post-man-update-record

We can also use the GET /api/bears call we used earlier to see that his name has changed.

node-api-postman-all-updated

Deleting a Bear DELETE /api/bears/:bear_id

When someone requests that a bear is deleted, all they have to do is send a DELETE to /api/bears/:bear_id

Let’s add the code for deleting bears.

// server.js

...

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
	...

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

	// get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
	.get(function(req, res) {
		...
	})

	// update the bear with this id (accessed at PUT http://localhost:8080/api/bears/:bear_id)
	.put(function(req, res) {
		...
	})

	// delete the bear with this id (accessed at DELETE http://localhost:8080/api/bears/:bear_id)
	.delete(function(req, res) {
		Bear.remove({
			_id: req.params.bear_id
		}, function(err, bear) {
			if (err)
				res.send(err);

			res.json({ message: 'Successfully deleted' });
		});
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

Now when we send a request to our API using DELETE with the proper bear_id, we’ll delete our bear from existence.

node-api-postman-delete

When we try to get all the bears, there will be nothing left of them.

node-api-postman-get-all-nothing

Conclusion

We now have the means to handle CRUD on a specific resource (our beloved bears) through our own API. Using the techniques above should be a good foundation to move into building larger and more robust APIs.

This has been a quick look at creating a Node API using Express 4. There are many more things you can do with your own APIs. You can add authentication, create better error messages, add different sections so you’re not just working with bears.

Sound off in the comments if you have any questions or would like to see any specific topics in the future.

Want More MEAN?

This article is part of our Getting MEAN series. Here are the other articles.

Chris Sevilleja

Design, development, and anything in between that I find interesting.

View My Articles

Stay Connected With Us
hover these for magic

Follow

Get valuable tips, articles, and resources straight to your inbox. Every Tuesday.

  • Iladarsda

    An example of customer OAuth (user+pass+token) implementation (e.g. to serve multiple clients) would be very useful!

    • Frenky Harry Saputra

      +1 Please please please, Chris… :))

      • http://scotch.io/ Chris Sevilleja

        This is definitely on my to do list. It will be coming soon along with a lot more authentication stuff.

        • Jesús Mur

          It could be very useful for me :)

    • santi

      please!!

      • http://scotch.io/ Chris Sevilleja

        I’m currently working on one as we type. Just want to make sure that everything is solid. Definitely have to be careful we’re not putting out bad information for security articles.

        I wish I could give a timeline but I am working on it!

        • Teo

          Does this stuff is so complicated? I. not sure if i really want to continue learning this, if for an experienced developer in these technologies would take at least 2-3 months …

        • Tim

          I can’t wait!!

    • Connor James Leech

      +1 I’m looking for a tutorial on how to secure a node.js API so my website and angular cordova app can both use it

  • Carlos Corvaia

    Awesome Article but for the call /api/bears/:bear_id , I think you have to use findById. If you use find it will just return an array of all the bears in the DB.
    Again Awesome Article. Keep em coming =)

    • http://scotch.io/ Chris Sevilleja

      Thanks. Fixed!

  • Cory Asato

    Thanks, great little project to get familiar with the router! Much appreciated. Gonna try and apply it to your Easy Node Auth series.

    As with what Carlos noted, findById() on the :bear_id gets a request for a specific bear. If you have multiple bears in your db, find() will respond with an array of all bears regardless of passing the unique id in the url.

    • http://scotch.io/ Chris Sevilleja

      Thanks a lot. I’ve fixed the article.

  • Jose Rafael

    As always, great stuff, Chris!

    • http://scotch.io/ Chris Sevilleja

      Thanks Jose!

  • Etienne Soulard Geoffrion

    is there a particular reason that when i run your project locally, i do not get any response from the server.. not even localhost:8080/api/

  • fohtoh

    Awesome Tutorial. Very clear!! Just found your site, love the articles so far!!

    • http://scotch.io/ Chris Sevilleja

      Glad to hear it! Thanks for reading. Any other articles you’d like to see?

      • fohtoh

        I haven’t had a chance to scan through all your tutorials so far, so maybe you already have it. But it would be cool to have a guide on testing your node apps. So maybe using Karma, or just Jasmine. Maybe throw in some protractor etc..

        Keep up the great work.

        • http://scotch.io/ Chris Sevilleja

          Testing articles are definitely in the pipeline. Admittedly it’s a little bit down the list, but we’ll get to it as soon as we can.

  • rowteeme

    Hey Chris, thanks for another great tutorial. I seem to be stuck right after pulling in bear. Here’s a screenshot of basically everything on my screen: http://cl.ly/V0nj. Do you have any ideas why node can’t seem to find the module?

    • rowteeme

      Ah, it was my file structure – had package.json and server.js within app instead of on the same level. Feel free to disregard!

  • Alejandro Paciotti

    Great tutorial, as always clear, always as didactic.

  • Pingback: Decaying Code | Community Update 2014-04-16 – #angularjs, #stringjs, #nodejs, #KendoUI going #OSS, #aspnet and more

  • Ting Layhort

    Thanks, for your tutorial.

  • Paul

    Ideal article on Express 4 found your site via Node weekly, have you bookmarked in my node folder.

    • http://scotch.io/ Chris Sevilleja

      Sweet!

  • pelumini

    Thanks for taking us to Express 4

  • Frenky Harry Saputra

    I didn’t get JSON response when using:

    router.get(‘/’, function(req, res) {
    res.send(‘hooray! welcome to our api!’);
    });

    The server just return string “hooray! welcome to our api!”

    But in your screenshot the server return JSON message

    http://scotch.io/wp-content/uploads/2014/04/node-api-postman-test.png

    :/ i’m confused…

    • Hugo Habel

      Same happened to me, don’t pay attention to it. Later on the tutorial, they add the line that returns the json.

      res.json({ message: ‘hooray…’});

      • http://scotch.io/ Chris Sevilleja

        Sorry about that. I wasn’t getting notifications for Disqus comments for some reason. I’ve updated the tutorial to spit out JSON from the start. Thanks for reading.

  • Fran Miranda

    Good intro to express 4.
    I don’t know if any of this changed in express 4 but according to best practices errors should be handled by the error middleware. Routes can access a third parameter (usually called next) that should be called upon error. Also, if an error is encountered it you should: return res.send(error) so all the code below doesn’t get executed.
    ps: Error middleware is any middleware function with 4 parameters:
    app.use(function(err,req,res,next){…})

  • jorge

    Amazing tutorial, I’ve just found your website and I’m totally impressed by the quality of your articles… God bless you!!! 8^)

    • http://scotch.io/ Chris Sevilleja

      Thanks jorge!

  • Paul

    Just curious if anyone is experiencing memory leaks while following this tutorial?

  • Maksim A

    Awesome tut. Wanted to suggest you to check out yeoman with anglular-fullstack generator. I am scaffolding with it all your examples. It generated quite a lots of code and have tons of cool stuff built in it.

  • Charlie

    Great Article! How can I enable CrossDomain in this new router?

  • Pingback: Noticias 28-04-2014 - La Web de Programación

  • Pingback: Updates & Top Posts Related to Our Work @ Deconstructed | Deconstructed

  • JC

    Easy to follow tutorial, Thanks!

    I’m curious how these Router changes in Express 4 will look when you separate your routes into a directory called ./routes/. Can you give an example?

    • http://scotch.io/ Chris Sevilleja

      You would create the normal router inside of your separate files. So for a file called /routes/api.js

      var
      router = express.Router();

      router.get('/', function(req, res) {
      res.send('blah');
      });

      module.exports = router;

      Then inside your server.js file, you would be able to call it:

      app.get('/api', require('./routes/api'));

      You could call multiple files like this. Try that out and let me know how it goes. My syntax could be off, but that’s the gist of it.

      • yoyoma

        it needs to be app.use on the last line still, other than that…works great

      • Ric

        For me doesn’t work – Any other option? Thanks

  • Mike

    Thank you! I have an issue though when implementing your solution. Responds are not encoded in UTF-8. For example: res.json({ message: ‘Μη λατινικοί χαρακτήρες’ }); will not return the correct message. Can you try it and let me know how it goes? Thanks!

    • Mike

      It works correctly. Please ignore…
      Not the sharpest knife in the drawer after midnight. Thank again for the great post!

  • Jimmy Engström

    Very good tutorial!
    I would love to see this using a TDD approach.

  • Guest

    if (err)
    res.send(err);
    res.json(bear);

  • manan vaghasiya

    if (err)
    res.send(err);
    res.json(bear);

    these lines are wrong. a return statement should be used in if block or the last line should be in else block. dont you think?

    • jorge

      Keep in mind that res.send() call res.end() for you.

      • manan vaghasiya

        But that doesn’t mean the function execution is stopped, remainings of the function will still be executed.

        • jorge

          Of course it doesn’t mean that the function execution is stopped, but for the sake of simplicity, Chris code es perfectly valid, and it shows how after res.send( ) you cannot send any other response.

          • chug2k

            I found a need to put an else in there…

  • Adam Grant

    Awesome tutorial, thanks man.

  • Pingback: Amazon EC2 + MEAN | Juan Antonio Medina Iglesias

  • Wisam Zaghal

    Fantastic easy-to-follow and understand tutorial. If I may make a suggestion : I would love to see this modified to include an actual mongodb database that we set up together.

  • Pingback: Development | Pearltrees

  • alexander

    Thank you for the tutorial! I ran into a problem with my router.route(‘/bears’). When I tried testing the ‘.post(function(req,res)…’ in Postman the bear would not be created. Postman took a long time to ‘fetch the data’ and then eventually responded with, ‘could not get any response.’ Then when I skipped ahead to the ‘.get’ part, my nodemon crashed in the console and said the ‘.’ in ‘.get’ was a ‘SyntaxError: Unexpected token . ‘ I double checked that I’m running version 4.0.0 of Express, but it seems like the .post and .get routing isn’t working for me like it’s working for others. Any help would be extremely appreciated. Thanks!

    • Melissa

      .post worked for me. .get gives me the same unexpected token error

    • Melissa

      I solved it by removing the semi colon right before “.get” – at the end of the .post statement.

  • Ric

    Nice article! I’d like to see OAuth (user+pass+token) implementation when you have time.

  • Paxi

    This article was very helpful! But I have a question about it. What if I have a Schema which is contains an array, and I want to push an element? Could anyone help me please?

  • Teo

    Thanks , great article , can you please add the OAuth please …

  • Tim Callaghan

    Just thought I’d leave a note and say many thanks Chris. I’m a total n00b to Node/Express and this tutorial have been very useful to me.

  • Anders Östman

    Great tutorial!

    In the discusson below you talk about error handling, and that it should be handled in a separate middleware.

    Lets say i try to query a bear that doesnt exist, Mongoose will create a err object, and we will res.send this.

    How would this look like instead if we where handling this error with a middleware?

  • G. J. J.

    Is there any reason why this is not working when I try to do anything with the API? POSTMAN times out and a response code ’0′ is returned. Attached is a screenshot. Note that I have intentionally changed your model of bears to users.

    • http://scotch.io/ Chris Sevilleja

      Can you try creating a basic route for the home page and testing that to be sure that your app is up and running and you can communicate to it.


      router.get('/', function(req, res) {
      res.send('hello');
      });

      You should be able to see hello in your browser at http://localhost:8080

    • http://www.ricardofilipe.com Ricardo

      I’m having the exact same problem, it’s like Mongoose hasn’t been started… I’m guessing we need to instantiate a connection, somehow. Any luck so far?

      • http://scotch.io/ Chris Sevilleja

        Are you able to see anything in the browser for a route for the home page?
        Route.get('/', function(req, res) {
        console.log('helloooooo');
        });

        This will help determine if it’s a server issue. Where is your MongoDB database hosted? Local or on an online service?

        • http://www.ricardofilipe.com Ricardo

          Hi, thanks for taking the time to help out.

          Everything related to express works just fine, so it’s definitely a Mongoose issue. All routes fire and the Middleware works perfectly, but the success callbacks for both .find and all other methods simply never fire, nor spit out the error. I can even read the body parameters just fine, just not inside the success callbacks.

          In fact copying the code on this tutorial doesn’t work either, so my guess is that something really is missing. My database is running locally, yes, and seems healthy enough.

  • Joel McCune

    So I will just come out and say it. I am a moron.

    Even though I have a positively useless degree after five years of school, now I am struggling to figure out how to lace together front end frameworks…but they are kind of boring without being able to put your own examples behind them. I was really struggling with figuring out how to do it. This tutorial is absolutely perfect, and you explained what middleware is as well…something else really vexing me! Thank you for walking a moron like me through it absolutely step-by-step and explaining everything.

    You may find it hard to believe, but it actually took me three times to get this thing working. This would be the moron part, yes. Now I have enough to build a simple REST endpoint and start fiddling with trying to figure out front end frameworks now. Thank you so much!

    It would be outstanding if you had the time to follow up and flesh out this article to show how to slide OAuth into the middleware. I might even do a happy dance!

  • Insane IT Skills

    This interactive tutorial gives you all the keys to a good start for a complete masteration of node.js by taking all the power of it.
    This course is regularly updated.
    https://www.udemy.com/nodejs-tutorial-from-scratch-by-examples

  • Pingback: Javascript | Pearltrees

  • Anthony Young

    Great tutorial Chris, I was wondering how I would add on a photo upload to the bear items?

    • Karan

      I’ve been trying to figure out how to do this as well. A tutorial would be really helpful.

  • Sigkill9

    Thank you! Your tutorials have been invaluable in getting up and running with nodejs development. and what a great looking site too! I raise my glass to you sir! Glenmorangie Bergundy Cask.

  • Byron Houwens

    I get a 404 error when running the first test with Postman. If I go onto localhost:8080 in a browser I get a “Cannot GET /”, but localhost:8080/api in the browser returns the JSON. I’ve copied and pasted the code too just in case, but get the same response. Anybody have any idea as to why this might be happening? I just can’t see the issue

    • guest

      you have to type localhost:8080/api

      • Byron Houwens

        Yea I did that but I just get the JSON returned as is.

  • fredy

    Thanks for share this tutorial with us! Very good :D

  • MarcoCodero

    i stucked at “Creating a Bear” (Post)

    posting in postman gives this:

    “TypeError: Object function ( options ) {

    return new Bear( options, ret.gith );

    } has no method 'save'

    at Object.handle … ”

    Any Ideas why its stoping at the save method?

  • Jameson Trinker

    How would you attach Angular to this app to consume the json we just created?

  • Pingback: [teklinks][28] Typescript, microsoft, task scheduler, freebies, REST, web app, IE .. | Blopes

  • http://www.kadiranilturgut.com Kadir Anıl Turğut

    Thanks for sharing this tutorial Chris.

  • Gregory Thompson

    This is honestly an amazing article. Using node.js for some time now but being like most devs I dabble in pretty much everything and this is so straight forward and concise but doesn’t slack in any area. It’s would be great for beginners and pros of JS. Great article guys.

  • http://grantgeorge.io/ Grant

    Great tutorial. I was looking for something to help me get started building out the back-end of my MEAN-stack based application and this did just the trick. Thanks!

  • Joe Tagliaferro

    Great tutorial! Scotch is an awesome resource to me on a regular basis, as someone who is just diving into node. I was wondering if you still have intentions of expanding on this topic into api authentication. I am finding information on good practices very scattered and seemingly dated. Thanks.

    • http://scotch.io/ Chris Sevilleja

      We still have plans for that in the future. Not sure where it falls in the timeline though. I’ll try to get that article released sooner rather than later. I know a lot of people are looking for that topic.

  • Karan

    Awesome tutorial. Is there a similar way to implement image/file upload and download through POST and GET routes in a REST API as shown in this tutorial? If so, is there a good tutorial or link that would help in trying to do this? Thanks.

  • Jason Spick

    Chris, I just would like to compliment you on these tutorials. I have had a tough time getting some of these MEAN stack concepts and your tutorials have helped me greatly. Keep up the good work!

  • http://baffleinc.com Harel Tankengine Alexander

    UNREAL. Blown away at how easy this is.

  • http://avalaunchmedia.com/ Brandon Buttars

    Thanks. This tutorial is exactly what I needed. I’m trying to learn Angular and needing to connect to a Mongo database. This tutorial gave me exactly what I needed. Works like a charm.

  • Miau

    I liked the tutorial!, could you please comment how to improve the POST method?, because if it doesn’t have properties should return an error and don’t go to the database.