Building a Node.js API
In the previous chapter, you built a fully functioning Angular app for posting status updates. In this chapter, you will build an API for it to get a list of all the posts and to make a new post. The endpoints will be as follows:
- GET /api/posts returns a JSON array of all the posts. This is similar to what you had in $scope.posts.
- POST /api/posts expects a JSON document containing a username and post body. It will save that post in MongoDB.
The Stock Endpoint
To start, you’ll use Node.js and Express to build a stock /api/posts endpoint. First, inside a new folder, create a package.json file like the following:
{ "name": "socialapp" }
The name can be anything you want, but try to ensure it doesn’t conflict with an existing package. The package.json file is the only thing you need to make a directory a node project.
Now that you have this, you can add express and body-parser as dependencies:
$ cd <path-to-project-folder> $ npm install --save express $ npm install --save body-parser
body-parser is used for express to read in JSON on POST requests automatically.
The --save flag saves the dependency to the package.json file so you know what versions of what packages the app was built with (and therefore depends on). In fact, if you open your package.json, you’ll see something similar to this:
{ "name": "socialapp", "dependencies": { "body-parser": "^1.4.3", "express": "^4.4.4" } }
Now that you’ve done this, you can require(‘express’) to include it in a node script.
Create a server.js file with the following contents:
var express = require('express') var bodyParser = require('body-parser') var app = express() app.use(bodyParser.json()) app.get('/api/posts', function (req, res) { res.json([ { username: 'dickeyxxx', body: 'node rocks!' } ]) }) app.listen(3000, function () { console.log('Server listening on', 3000) })
Try running this file:
$ node server.js
You can access it in your browser at //localhost:3000/api/posts. You should see that your stubbed JSON comes back.
You now have the basic Node request in place, so you need to add the POST endpoint for adding posts and back it against MongoDB.