This project uses Node.js and Express to build a basic REST-based chat server. You will also be plugging in a basic Angular app to make your first full stack application!
-
Clone this project
-
Run
npm init
to to create ourpackage.json
. -
Install the packages we'll need — express and body-parser
npm install --save package-name
-
Require express and body-parser in
index.js
-
Initialize express and assign it the app variable
var app = express()
-
Start listening to a port using
app.listen(3000)
We need to send our client-side code (located in the assets folder) to the user when they go to our site. We'll also want express to automatically parse stringified JSON data coming in and assign it as a JS Object to req.body
.
The express and body-parser packages provide an easy way to do these two tasks. After var app = express()
insert these two lines:
app.use(express.static('assets'))
app.use(bodyParser.json())
We will discussing, in much more depth, how this works tomorrow!
-
Create an array for storing your messages temporarily. You could call the variable
messages
. Think about what scope this variable should be placed in. We need to be sure we keep our messages from previous requests or at least until our server is restarted. -
Write a new GET endpoint that returns our array of messages. It will look something like this:
app.get('/messages', function (req, res, next) {
res.status(200).json({ messages: messages });
});
- Test your server. Run it with
nodemon index.js
and use Postman to make a GET request to/messages
. Add some default messages to themessages
variable to make sure it is returning data the way you would expect.
Lets create our endpoint to POST a new message. This will be structured similarly to our GET endpoint. Let's start by logging req.body
.
app.post('/messages', function (req, res, next) {
console.log(req.body);
});
Let's test this out in Postman
-
Select 'POST' from the request method dropdown next to your URL
-
Set the Content-Type of the request
-
Select the 'Body' tab
-
Select the 'raw' radio button
-
Select 'JSON (application/json)' in the dropdown menu to the right of the radio buttons
-
Add some JSON data to the text-area in this tab. Let's start with something like:
{
"message": "Wubba Dubba Lub Dub!"
}
- Smash the 'Send' button!
Check to see that our console.log(req.body)
code logged something to the terminal. It should look something like { message: 'Wubba Dubba Lub Dub!' }
. If you are getting errors, check the formatting of your JSON. It is important to use double quotes around both the key and the value.
Brilliant. Let's finish up this endpoint.
-
Add the message from
req.body
to our array ofmessages
. -
End the response using the
status
andjson
methods to send back that our full array of messages just like we did for the GET endpoint. It will look similar to this:
app.post('/messages', function (req, res, next) {
messages.push(req.body.message);
res.status(200).json({ messages: messages });
});
- Test this out again in Postman! You should get a response this time.
Go to http://localhost:3000 in your browser. The app should be up and running!
Take a few minutes to browse through the client-side code provided. It should all be very familiar.
Now that we have basic functionality, let's do some server-side data manipulation. We want to add a timestamp to each message and display it.
First, lets change our messages
array — from an array of strings to an array of objects. This way, we can assign multiple properties to each message: time
and message
. Let's do this by pushing a newly created object to our array instead of just the message sent to us.
messages.push({ message: req.body.message, time: new Date() });
Second, we need to make a small adjustment to our client-side code to handle this new data structure. The ng-repeat of over our messages will need to look simlar to this:
<div ng-repeat="message in messages track by $index">
{{message.message}} : {{message.time}}
</div>
As easy as that, we've added new server-side data and passed it back to our client-side code. You may have noticed that the date is displaying poorly. Look up the Angular documentation for the 'date' filter and try to set it up so that it shows something along the lines of '5:22 PM'.
Try adding some more sophistication to your chat client, such as a username or profile picture. Allow the user to specify their username when posting a message.
If you see a problem or a typo, please fork, make the necessary changes, and create a pull request so we can review your changes and merge them into the master repo and branch.
© DevMountain LLC, 2017. Unauthorized use and/or duplication of this material without express and written permission from DevMountain, LLC is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to DevMountain with appropriate and specific direction to the original content.