Intro to Back-end Development with NodeJS
12 Apr 2016Installing NodeJS
Download and install the latest version of NodeJS from the NodeJS site.
If you opt to use a cloud IDE such as Cloud9, NodeJS will come already installed with your workspace.
To test that NodeJS is installed correctly in your environment, type in node -v
. This should respond with a version number.
Creating our first back-end server
Anywhere in your workspace environment create a folder, say backend
. Inside that folder create a file called server.js
server.js
Running our back-end server
We can start this server running by issuing the command node server.js
from the same folder.
We can see this server running by pointing a browser to localhost:3000
. It should respond with the response string hello world
.
(For Cloud9 users, point your browser to: https://your-workspace-name.c9users.io/
).
Returning a JSON response
As our response we can return some data in JSON format. For now we’ll just hard-code that data as a JSON variable and pass it back as the response.
server.js
Restart the server by pressing ctrl-c
and then issuing the node server.js
command again. Refresh the browser to see the new JSON response.
Nodemon
To save having to restart the server with each change to the server code, install nodemon
. This is a NodeJS module that monitors the server file for any changes.
You install this by issuing the following command: npm install nodemon
From here on in, you can run the server with: nodemon server.js
and this will monitor the code file for any changes and automatically restart the server as needed.
Calling our server from a front-end
Let’s complete the exercise by coding a simple front-end that will make an AJAX request to our back-end server.
First add this line to server.js
(first line in function onRequest) so that the back-end can be called from anywhere.
response.setHeader('Access-Control-Allow-Origin','*');
Next, code this simple front-end by creating a folder, say frontend
, anywhere in your workspace, and adding these files to it. (This should be very straightforward HTML/CSS/JS from our previous sessions.)
index.html
style.css
app.js
Run this front-end by opening the index.html
file in a browser. It should display the one-line html we’ve coded.
(For Cloud9 users, remember to set the url in the $.get()
AJAX call to https://your-workspace-name.c9users.io/
).