I have spent one day (so far) learning expressjs — a node.js framework for a web application server. After a couple of hours I think I might be hooked, but I also have a lot more to learn. I wanted to document some of the lessons that I learned going through this process. I will cover the following topics in this article.
- Getting started with express
- Starting up the server
- Using the body-parser middleware
- Enabling cross original resource sharing (CORS)
- Debugging with console.log
- Setting status code and response
Getting Started with Express
Getting started with express is pretty easy. The prerequisite for expressjs is that you have downloaded and installed node.js. Secondly, you should be pretty comfortable operating in a terminal/command-line environment.
Now that we are ready to go we need to create the package.json file that will specify our project settings and dependencies. At first our only dependency will be express itself. Here is what the package.json file looks like.
{
"name": "simple-json-example",
"description": "Simple JSON Example",
"version": "1.0.0",
"private": true,
"dependencies": {
"express": "4.x"
}
}
I am using Express 4.x version, but you can also just use the latest version by substituting “4.x” with “latest”. My project is a simple JSON parsing sample. Based on the message that is posted, our simple server will respond with a simple text message. Really easy.
The next thing we need to do is to install express using the node package manager (npm). To do this, open up the terminal/command-line and browse to your project folder where you created the package.json file. Then run the following command (excluding the dollar sign).
$ npm install
This should create a new folder called node_modules that will contain the express code.
Now we are ready to start coding up our express application.
The code for the application will be placed in a new file named server.js.
Start by using the require()
function to load the express module.
Then start up a new application using the express constructor.
var express = require('express');
var app = express();
Simple enough so far. Now, let’s create a new handle for the POST that the client will send to the server. The client code will send a POST to http://localhost:8080/sample-json so we want to specify a post handler for the /sample-json path.
app.post('/sample-json', function (req, res) {
//do some work
});
The second argument to the method is our anonymous function that will be called by express.
The function will receive two objects: first the request
object and secondly the response
object.
Right now we are not doing anything. We will get to that shortly.
Finally, we need to tell our application to listen on a specific port. I am using port 8080 to avoid any conflicts with an existing web server that may be running on port 80. I am also logging out a message to my console letting me know that the server has started successfully.
app.listen(8080, function () {
console.log('Server started and listening on port 8080');
});
In summary our server.js file looks like this.
//require expressjs
var express = require('express');
//start application
var app = express();
app.post('/sample-json', function (req, res) {
//do some work
});
//listen on port 8080
app.listen(8080, function () {
console.log('Server started and listening on port 8080');
});
Starting up the server
Now that we have our application coded up (as simple as it is) we want to get it going. It’s really easy. Just run the following command.
$ npm start
You should see the console message indicating that it started successfully.
$ npm start
> receive-json@1.0.0 start /Users/brian/blog/express
> node server.js
Server started and listening on port 8080
Using the body-parser Middleware
As of express 4.x the body parsing middleware was separated into it’s own package that you will need to install. In express 3.x this was built into the express package. So, let’s add this new dependency to our package.json file. Just add a new line specifying this new package to install.
{
"name": "receive-json",
"description": "receive JSON",
"version": "1.0.0",
"private": true,
"dependencies": {
"express": "4.x",
"body-parser": "latest"
}
}
Then, run the npm install command again to install this new dependency.
$ npm install
Next, we need to require this new module in our server and configure our express application to use the body-parser middleware.
var bodyParser = require('body-parser');
The body-parser middleware can decode a form POST easily.
Note that the content-type must be specified as application/x-www-form-urlencoded
.
Just add the following code to your server.js file.
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
The body-parser middleware can also parse JSON text. Note that the content-type must be specified as application/json. To parse the JSON text in the request body just add the following code to your server.js file.
app.use(bodyParser.json());
Again very simple!
The parsed data is stored in the body
property of the request object.
To summarize this here is the complete code for logging out the form data that is posted to our server.
//require expressjs and middleware
var express = require('express');
var bodyParser = require('body-parser');
//start application
var app = express();
// parse application/x-www-form-urlencoded
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
app.post('/sample-post', function (req, res) {
//log out the form data
console.log('POST data : %j', req.body);
});
//listen on port 8080
app.listen(8080, function () {
console.log('Server started and listening on port 8080');
});
Enabling CORS
Next, I want to include the CORS module for enabling cross origin resource sharing. You can read more about CORS and their suggested implementation for expressjs. This enables my server to respond to requests from any domain. My client request is coming from a separate domain and my express application is listening on the localhost domain.
First, we need to install the cors module. Let’s add it as a dependency of our project in the package.json file.
{
"name": "receive-json",
"description": "receive JSON",
"version": "1.0.0",
"private": true,
"dependencies": {
"express": "4.x",
"cors": "latest",
"body-parser": "latest"
}
}
Of course we need to run the npm install command again to install the new module.
$ npm install
Then we require the cors module and allow all CORS requests. You can read more about the CORS module and the various configuration options on the GitHub project page.
var cors = require('cors');
app.use(cors());
That’s it. :)
Debugging with console.log
As you have already seen in the examples that I have provided I am using the console.log() method to display debugging messages to the standard output.
These show up in the terminal window as you interact with your application.
I cannot stress enough how helpful these are when it comes to debugging and troubleshooting your application.
I am also using the printf
style formatting of the messages.
Here is a quick cheat sheet for using printf formatting.
Setting status code and response body
Finally we can start to do some application logic!
For my sample request I am expecting a form variable named json
that contains a JSON string.
The form post is parsed and stored in the req.body
parameter by the body-parser middleware.
I want to first validate the request, then parse the JSON, and then return some text back to the client based on the message that is sent.
Here is my complete server.js file.
//require expressjs and middleware
var express = require('express');
var bodyParser = require('body-parser');
//start application
var app = express();
// parse application/x-www-form-urlencoded
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
app.post('/sample-post', function (req, res) {
//validate post
if (!!!req.body.json) {
console.warn('The json POST variable was not provided.');
res.status(500);
return;
}
//body-parser middleware will decode the form post
var jsonString = req.body.json;
console.log('json string : %s', jsonString);
//parse the JSON string
var json = JSON.parse(jsonString);
console.log('parsed json : %j', json);
//determine response
var respondWith =
!!json.msg && json.msg == 'Hello' ? 'Hello World!' : 'Goodbye!';
//send response
res.status(200);
res.send(respondWith);
});
//listen on port 8080
app.listen(8080, function () {
console.log('Server started and listening on port 8080');
});
Let me run through each of the segments of the application code above.
- Lines 15-19: I am validating the request by checking for the existence of the
req.body.json
variable.json
is the name of the form field that is being POSTed to the server. If the json field has not been provided, then I am logging out a warning to the console and returning a 500 status code to the client. - Lines 22-23: I am just getting the value of the json field and logging it out to the console.
- Lines 26-27: I am using the
JSON
class to parse the json string and logging out the JSON object. - Line 30: I am checking that the JSON object has a property named
msg
, and checking the value of it. If the value ofmsg
is “Hello”, then I reply with “Hello World!”, otherwise I reply with “Goodbye!“. - Lined 33-34: I am setting the status code to 200 (success) and setting the response text that will be sent to the client.
I hope this very simply example of using expressjs shows both the simplicity and the power of using expressjs with node.js.