Node.js – What is the Difference Between response.send(), response.end() and response.write() ?

Express JS

JavaScript Logoresponse.send() sends the response and closes the connection, whereas with response.write() you can send multiple responses.

In this article, I will explain the difference between response.send(), response.end() and response.write(), and when to use each one. When you’re working with the Express.js framework, you’ll probably most frequently be sending a response to a user. This means that regardless of which HTTP verb you’re handling, you’ll pass a function as the handler for that endpoint. This function will receive two arguments: the request object and the response object. The response object has a send() method, an end() method and a write() method, and in this article we’ll get to know the differences between them.

So, let’s start with the main issue, which is that the response.send() method is used to send the response to the server. Now this makes sense and in some cases, it’s actually the perfect tool. Problems can arise, though, if you’re not entirely sure what the response.send() method actually does. Well, in a nutshell, it does two things; it writes the response and also closes the connection. So, this seems like a win-win, right? Well, in some cases it is, but if you don’t want to close the connection on your first write, then the response.send() method may not be the right tool. When this happens, you’ll need to use a combination of response.write() and response.close(). So, let’s take a look at a few examples, to see just how this works.

Get the example code from GitHub

If you clone this repo: github.com/kevinchisholm/video-code-examples/tree/master/node-express/response-send-end-write-difference, you can clone the example code locally and edit the code yourself.

Trying to use the response.send method more than once per request – Example # 1

Run Example # 1 in your terminal with the following command: node example-1.js, then point your browser to: http://localhost:5000/. Now you’ll see this: “This is the response #: 1“. There are two problems here, however, the first of which is that any responses after the first one are never sent. This is because the send method of the Express.js response object ends the response process. As a result, the user never sees the messages “This is the response #: 2” or “This is the response #: 3”, and so forth.

The second problem is that the send method of the Express response object sets the Content-Type header, which is an automatic action. So, on the first iteration of the for-loop, the Content-Type header is set (i.e. “This is the response #: 1”). Then on the next iteration of the for-loop, the Content-Type header is set again because once more, we are using the response.send() method (i.e. “This is the response #: 2). But, we have already set the Content-Type header in the first iteration of the for-loop.
Because of this, the send method will throw this error: “Error: Can’t set headers after they are sent”. So, our application is essentially broken, but we don’t want users to have an error in their consoles. And more importantly; our back-end logic is not working correctly.

Using the result.write method – Example # 2

So, using the result.write method run Example # 2 in your terminal with the following command: node example-2.js. Now point your browser to: http://localhost:5000/. As you can see, there is still a problem with our code. Depending on your browser, either you will see only the first message or you will see none of them. This is because the response has not been completed. So, I’ll just mention here, that not every browser handles this case the same, which is the reason why you may see one message, all of the messages or none of them. But you should see that the request is “hanging” as your browser will stay in that “loading” state.

So, open your developer tools (e.g. FireBug or Chrome Dev Tools), and then look at the network tab. You’ll see that all five responses did, in fact, come back to the client. The problem is, the browser is waiting for more responses.
At some point, the request should time out and you can see all messages in the browser. This behavior can vary between browsers, but it is not the correct experience.

result.end fixes the problem – Example # 3

Run Example # 3 in your terminal with the following command: node example-3.js, then point your browser to: http://localhost:5000/. You will now see all of the messages in the browser, which means that here, in Example # 3, the problem has been fixed. We see all of the messages generated by the for-loop and the response completes successfully with no console errors. So, we’ve solved the problem by using a combination of of response.write() and response.close().

First we set the Content-Type header, just to get that task out of the way. Then, in each iteration of the for-loop, we used response.write() to send a message back to the client. But since response.write() does not set any headers or close the connection, so we were free to call response.write(), to send another response to the client. And once the for-loop was completed, we used the result.end() method to end the response process (i.e. we closed the connection). This said to the browser: “we’re done; go ahead and render the response now and don’t expect anything more from me.”

Summary

In this article, we learned about the difference between response.send(), response.end() and response.write(). During this discussion, we found that response.send() is quite helpful in that it sends the response and closes the connection. We saw that this becomes problematic, however, when we want to send more than one response to the client. But, fortunately, we discovered that this is easily solved by using a combination of response.write() and response.close(). We used response.write() to send more than one response, and then used response.end() to manually end the response process and close the HTTP connection. So, useful steps and easily solved problems.!

Handling HTTP POST Requests with Express.js

Express JS

Node.js LogoLearn how to access the body of an HTTP POST request using the Express.js framework and body-parser module.

Forms are a common component in web applications. When a user submits a form, that data is sent to the back-end for processing. To process that data, the web server must understand how to access it. Popular web server languages include Java, .NET, PHP, Python and Node.js. In this article, we’ll learn how to access the POST data sent to a Node.js web server using the Express.js framework. To get started, you can go ahead and clone the following github repository: Handling POST requests with Express and Node.js.

And you’ll find instructions on how to run the code in the Github page.

package.json

The package.json for this project is pretty straightforward, and we’ll only need the body-parser and express Node.js modules. We also create a scripts property so that running the example code requires a simple command: npm start.

Requiring the modules we need – Example # 1:

In Example # 1, we’ve imported the Node.js modules that we need. The Express module takes care of the heavy lifting with regard to fulfilling web requests. NOTE: If you’re not familiar with the Express Node.js module, please see my earlier blog post on this subject:  Set up a Node / Express Static Web Server in Five Minutes.

We also import the body-parser Node.js module, which has the critical role of parsing the body of an HTTP request. When it comes to processing a POST request, this is important. And the path Node.js module helps express to construct a file path.

bodyParser.json and bodyParser.urlencoded – Example # 2:

Now, here in Example # 2, we tell express to use the bodyParser.json middleware, which provides support for parsing of application/json type post data. We also tell express to use the bodyParser.urlencoded middleware, which provides support for the parsing of application/x-www-form-urlencoded type post data.

Creating the node.js web server – Example # 3:

In Example # 3, we use express.static to set up the static assets folder, the main purpose of which is to help the working example function in a browser, with minimal effort. For more information on express.static, please see my earlier blog post in Express mentioned above. In this example, we use the app.post method, which tells the Express module to wait for an HTTP request at the /form route that leverages the POST HTTP verb. So, when the user sends a POST request to the /form route, Node.js executes the provided callback, which is the second argument passed to the app.post method.

The app.post callback takes two arguments, the first of which is the request object (i.e. “req”). The second is the result argument (i.e. “res”). We use the res.setHeader method to set the Content-Type header to application/json, which tells the user’s browser how to properly handle the returned data from the request.

NOTE: We wrap the rest of the callback code in a setTimeout, the purpose of which is to mimic a slow internet connection. Otherwise, the working example will move too fast for most to comfortably follow.

Inside the setTimeout, we use the res.send method to send the result body back to the user, and here we’re sending a serialized JSON object. To construct this object, we access the body property of the req object (i.e. the request object), which is why we have implemented the bodyParser.json middleware. And this is what allows us to parse the properties of the request body. In this example, we are expecting firstName and lastName POST parameters, which will allow us to access the req.body.firstName and req.body.lastName properties, to build the JSON for our result object.

To see this code in action, just follow these steps :

  1. Clone the git hub repository: https://github.com/kevinchisholm/video-code-examples/tree/master/node-express/handling-POST-requests-with-express
  2. Follow the instructions in the readme to set up the code
  3. Point your browser to: http://localhost:3000
  4. In the web page, enter some text into the two input boxes, and then click the “Submit” button
  5. Notice the logging statement in your node.js terminal
  6. Notice that the text you entered displayed in a browser message

You might also want to take a look at the Network tab in your Web Developer Tools, which allows you to see the actual network request that goes to the web server. You’ll be able to inspect the POST data sent, and the JSON data returned.

Viewing the working code example

Here’s what happens when you submit the data in the browser:

  1. The JavaScript in www/js/form-handler.js makes an AJAX POST call to the route: /form.
  2. The object sent in the POST request is: {firstName: XXX. lastName: XXX}. (NOTE: “XXX” is whatever value entered into the form’s text inputs.)
  3. Our Node.js web server intercepts the HTTP request to /form.
  4. Our Node.js web server parses the body of the HTTP request and constructs a JSON object.
  5. The XMLHttpRequest for the AJAX call is this JSON object.
  6. The browser displays the data from this JSON object in the browser.

Nothing too fancy here, just illustrating the “round trip” of our HTTP POST request.

Summary

In this article, we learned how to handle POST requests with the Express node.js module, and we talked about the need for bodyParser.json and bodyParser.urlencoded. We also learned how to listen for a POST request to a specific route, and how to access the POST parameters in the HTTP request body. Now, while the working example is simple, it does allow you to inspect every step of the process. If you look at your browser’s network tab, you can see the HTTP POST request go out, and then return. What happens during the server-side processing of that request is what you see in our Node.js code: server.js.

So, a lot to digest at first, but I’m hoping that this it will get you started with your next form-based Node.js application!

Introduction to Express.js, the Node.js web application framework

Express JS

Node.js Logo - expressExpress.js provides the kind of abstraction that lets you stay out of the weeds and focus on your application code.

While the low-level nature of Node can be an asset, it can also be somewhat of a curse because when you’re serving static assets, it can be tedious to detect routes and serve the correct static assets for an entire web page. Some examples of static assets are CSS files, images or JavaScript files. Now, the good news is, Express is a Node module that provides abstraction for these kinds of challenges. It’s popular, it’s used by large companies, and there’s strong community support for it, all of which make this a solid choice.

Why Express?

The main goal of Express is to provide an application framework, and getting started is simple. Take a look at the code samples, which you can clone at the following Github repository: Introduction to Express.js, the Node.js web application framework. You’ll find instructions on how to run the code in the Github

package.json

The package.json for this project is simple: the single dependency is express.

The get() Method – Example # 1

In Example # 1, we call the get() method of the app variable, and we pass the string “/” to the get method. This tells Express.js how we want to handle any GET request to the root of the application. (NOTE: GET is an HTTP verb, other examples are POST and PUT.) In Example # 1, we are sending back a simple HTML page, and we have created the HTML by constructing a string that represents that HTML code. This happens in the “HTML” variable. We then call the send() method of the result object, sending our HTML back to the user. Now run Example # 1 in your terminal with the command node example-1.js, then navigate to http://localhost:3000/ in your browser. There you will then see “This is Example # 1”.

The use() method – Example # 2

Example # 2 is much shorter than Example # 1 because we have not hard-coded our HTML. Instead, we have used the use method of the app object, which tells Express which folder we want to use for serving static assets. As a result, our JavaScript code is cleaner, and easier to read. Also, we’ve separated concerns. In other words, instead of hard-coding our HTML in our JavaScript file, we’ve put HTML where it belongs: in an HTML file.

Now notice how the web page in Example # 2 has an image. I included that to point out how Express handles this for us, even though we never had to write any JavaScript code that specifically waits for an image request. There is also a CSS file being served. In both cases, Express understands that WWW is our public web folder and it serves up static assets as needed, which certainly saves us a lot of time. Now run Example # 2 in your terminal with the command node example-2.js, then navigate to http://localhost:3000/ in your browser. There you will see “This is www/index.html”, which is a major improvement, as the HTML that the user sees is actually served from a static HTML file.

Adding Handlers for a Second Route – Example # 3

In Example # 3, we use the GET method to add a handler for when the user requests “/about“. In this case, we serve-up “/www/about.html“, which is just one example, but we could have added any specific route handlers needed. Now run Example # 3 in your terminal with the command node example-3.js, and navigate to http://localhost:3000/ in your browser. There you will see “This is www/index.html”. Now, click “About” in the upper-right-hand corner, to display the “About Us” page. You can then click “Home” and “About” over and over, to switch routes, because our JavaScript code in Example-1.js handles the alternation of these two routes.

Summary

In this article, we learned the absolute basics of Express, but in doing so, we also got to see how simple it is to use. In our discussion we saw examples of the get() method, as well as the use() method. I’m hoping that this was enough to illustrate the power behind this Node.js web application framework, and that it will get you well on your way to enjoying its usefulness.

Create a Node Websocket Server in Five Minutes

Node.js

Node.js Logo - node websocket serverLeveraging Express.js and the ws NPM module, it is possible to create a Node Websocket Server in less than ten lines of code.

The Websocket protocol provides full-duplex communication channels over a single TCP connection. In the past, web clients had to employ long-polling or the repeated pinging of a server in order to achieve this kind of “push” functionality. Now, Websocket technology eliminates the need for such outdated techniques. So, when a Websocket client connects to the server, a persistent connection is created, and the Websocket server can then push notifications to all connected clients. It is possible for the clients to send messages to the Websocket server as well, but I’ll cover that in a later article.

In this article, I’ll explain the bare-minimum code needed to create a Node Websocket server that can broadcast all incoming messages to connected clients. This should take us about five minutes, and less than ten lines of code. The beauty of Express.js is that it takes care of the heavy lifting with regard to the actual web server. The ws NPM module also plays a starring role in that it handles the Websocket communication layer, allowing us to expose an endpoint that accepts connections and messages from clients. Plus, we can broadcast messages to connected clients.

package.json

Above is the contents of package.json. There are only two dependencies: the Express.js framework and the ws module.

The Node Websocket Server – Example # 1

So, here in Example # 1 we have the entire working application. On line #s 3 through 9 we create our dependencies. I’ve grouped things in a way that I hope makes sense, but I’ll just point out that on a high level there are two things happening here. We require the modules that we need as constants: http, express, and WebSocket. Also, we create the constants app, server and websocketServer. These constants are the results of expressions. Now if you’ve ever worked with Express.js before, the app constant should be familiar to you; it’s simply an instance of the Express framework. The server constant is the result of calling http.createServer(), passing it our express.js instance (ie. “app”). And finally, the constant websocketServer represents our Websocket server.

Now let’s jump ahead for a moment to line # 30, where we start our web server. It’s not that there’s much going on here; it’s just that I wanted to point out that the server is started by calling the server.listen method, passing it the port to listen on (i.e. 3000). The second argument (the anonymous function) is optional.

Now let’s go back up to the top of the file. As you can see, the rest of the code is surprisingly simple. We create two event handlers, the first of which takes care of each Websocket client connection, and the second one processes each message that it receives from that client. On line # 12, we have the first event handler. We use the “on” method of the websocketServer instance to handler an incoming connection. This is somewhat similar to creating a handler for a GET or POST request in Express.js.

We pass the event as the first argument (i.e. “connection”), and then a function as the 2nd argument. The anonymous function that we provide contains the code that we want executed for each new Websocket client connection. This function also receives a Websocket client as its first argument. We have named this variable: “webSocketClient”. On line # 14 we provide some feedback to the Websocket client by sending it the first Websocket message: { “connection” : “ok”}. This is for demonstration purposes only, just so that we can see right away that the connection has been established.

Now inside of the anonymous callback, we set up the second event handler, which will process each message that this client receives. And similar to the connection event handler, we use the “on” method of the webSocketClient variable to handler an incoming message. We pass the event as the first argument (i.e. “message”), and then a function as the 2nd argument. The anonymous function that we provide contains the code that we want executed for each message received by this Websocket client.

Broadcasting the Message to All Websocket Clients

On line # 20, we start the process of broadcasting the incoming message to all Websocket clients. Using the forEach method of the Websocket.clients list, we iterate the list of websocket clients. And for each iteration, we provide a callback function. This callback function receives the currently iterated Websocket client as its first argument. So, we then use the send method of that client object, and send the incoming message (i.e. by sending one message to many recipients, we are “broadcasting” that message).

Testing the Websocket Server

Now if you copy all of the code from Example # 1 into a file and then execute it, you’ll have a running Websocket server on port # 3000. But that isn’t enough. Now we want to test our websocket server, and an easy way to do this is to use the Smart Websocket Client plugin for Google Chrome.

So go ahead and click this link to install the plugin, and once you’ve installed it, start the plugin by clicking the icon in the upper-right-hand corner of your Chrome browser.

smart-websocket-client-icon
smart-websocket-client-icon
smart-websocket-client-1
Smart Websocket Client

Once the Smart Websocket Client is running, enter http://localhost:3000 in the address bar and then click the “Connect” button. You should see { “connection” : “ok”} in the lower window, indicating that a Websocket connection was successfully established (see example # 2).

smart-websocket-client-2
Connecting
smart-websocket-client-3
Connecting Success Message

Example # 2

In the top window, enter any text, click the “Send” button, then you’ll see your message appear in the lower window. Now open a few more instances of the Smart Websocket Client and follow the same steps. If you place your Chrome browser tabs side by side, you’ll see that every message you’ve sent has been broadcast to every Websocket client. Congratulations!  You’ve just built a working Node Websocket server.

Example # 3

Now earlier in this article, I promised that we could create our Websocket server in less than ten lines of code. Example # 1 clocks in at 32 lines of code, but this is because I used whitespace and comments to make the code as readable as possible. So, in Example # 3, I’ve provided the condensed version of our Node Websocket server. This code is not very pretty, but as promised, it is a fully functional Node Websocket server that’s set up in less than ten lines

Set up a Node / Express Static Web Server in Five Minutes

Node.js

node express static web server

Setting up Node and Express as a Simple Lightweight Web Server for Your Single Page Application is Very Easy to Do.

Sometimes you just need a local web server.  Sure, you could use MAMP, but installing Apache, MySQL and PHP seems like overkill in some cases. I have used MAMP for years and it is terrific. In particular, when you need to run PHP locally and / or connect to a MySQL database, it’s the cats pajamas. But that was the standard 10 years ago. Nowadays, it’s very common to build a single page web application where all of the assets are static, data is pulled-in from a REST endpoint and all of the heavy lifting is done in the browser via JavaScript. In these kinds of scenarios, a static Node / Express server is a simple, easy and lightweight approach.

In this article I’ll explain the steps needed to set up a Node / Express Static Web Server. And the good news is that on this high level, the required steps are very simple. First, you’ll need to require the express and path modules. After that, you’ll create an instance of express, then set the port that the web-server will use. The next step, and the key-ingredient here is the express.static method. This tells Express.js that you want to serve static content from a specific folder. In that one line of code, you’ve done the majority of the configuration work.

So, not only will Express serve-up static content from that folder, it can do so for any subfolders as well. You can specify any folder in your project as the static web folder. And the beauty of it is that any folder outside of the one you specify will be hidden from public view, so your application code will be safe. When you pass the the express.static method to the use method of your express instance, you provide the details that express needs to serve your static content. Then finally, you use the listen method of your express instance to start the web server. We’ll take a closer look at the express.static method in Example # 2.

Now, I just want to remind you here that this article pertains to the specific occasions in which you need to serve static web assets locally. In other words, using a Node / Express static web server can be a very simple way to satisfy your need for a local web server, but may not be the best approach for your production needs. Technically, you could take the code that is detailed in this article and deploy it to your production server, and in theory it would work just fine. For this article, however, I’m just going to concentrate on providing a fast and simple way to get a local web server running so that you can test your front-end code (e.g. HTML, CSS or JavaScript).

The code samples can be downloaded here: https://github.com/kevinchisholm/node-express-static-web-server

Example # 1 – package.json

In Example # 1, we have the contents of package.json. Nothing too special going on here. But just note that our only dependency is the express module. Also, in the scripts property, I’ve set up the start command to execute the app.js file in the node web-server folder. This way, we can simply type npm start in the terminal, instead of node web-server/app.js (just a bit less typing).

Example # 2 – The Express Static Web Server

In Example # 2, we have the entire contents of our web server: 15 lines of code (and nearly 25% of that is comments!). The magic happens on line # 10:  We call the app.use method and pass it express.static, which also takes a couple of arguments. So this tells Express that we want to set a static folder. We then use the path.join method to tell Express where all static assets should be served from. In our case, it is the www folder. The two arguments passed to the path.join method are __dirname, which tells us the absolute path to the folder within which the current script is found, and then “../www” which is a relative path to the www folder.

Now, as I mentioned earlier, anything outside of your static folder is protected from public view. This means that while the folder you specify when calling the express.static() method (i.e. “../www”) is publically viewable, any folder that is a sibling or descendant of that folder is not available publically. This is not a critical factor when working locally (i.e, developing), but it does matter in production. In other words, you wouldn’t want your application code to be viewable to the general public. Nor would you want to make available any sensitive information that’s in your application code, such as a secret key or other credentials. So, as you can see, this is one of the key strengths of Express, which is the ability that it provides you to not only define your public/static folder in one line of code, but to also protect all of the other folders by default.

Express does all of the heavy lifting

A little earlier, I used the word magic. We both know that none of this is actually magic, but it sure feels like it. If you’ve ever created a Node web server manually, then you know two things: 1) It’s really easy, 2) It’s really tedious once you get past “Hello World”.  But Express hides all the tedium and makes serving static assets as easy as 1-2-3.

HTTP Headers

There is one downside here. Express does not set the appropriate content-type headers for the HTTP requests.  This is not fatal in most cases because this approach is simply meant to provide a very fast and easy way to set up a static web server. The actual web server works just fine, but keep in mind that content-type headers for files such as JPEG, PNG, CSS or JS will not be set accordingly. If that is a problem, then a simple static web server is probably not what you need and you should consider a more robust approach. So, hopefully, if you do need a simple static web server, this article was what you needed to get up and running quickly.

Summary

There are multiple options when it comes to setting up a static web server. One advantage to leveraging Node and Express.js, however, is that as a developer, you probably already have Node installed on your machine. So, in this case, you won’t need to install any additional software. You can simply import the Express framework, write about a dozen lines of code, and you have a static web server. This is probably not a server that you would use in production, but as you can see, it can easily solve the problem of quickly serving web content on your local machine. If you need to write moderately complex dynamic application logic, then you might need something a bit more advanced than what was discussed here. But for a basic static web server, this approach should get you going (hopefully in less than five minutes : – )

Creating a Simple JSONP API with Node.js and MongoDB

Node.js

MongoDB LogoBy leveraging the Node.js middleware “express”, we can create functionality for viewing, adding or deleting JSON data.

In a previous article: “Using Mongoose ODM to Connect to MongoDB In Your Node.js Application,” we learned the basics about connecting to a MongoDB database in a Node.js application. Because that article barely skimmed the surface of what is possible, we’ll take a few more baby steps here with our data. And for the sake of brevity, I’ll skim over the Mongoose.js details. If needed, you can refer to the article mentioned above for more details on that.

The goals for this article are:

  • Allow the user to view all data in the database
  • Allow the user to make a JSONP call to get all data
  • Allow the user to add a new name to the Sales database
  • Allow the user to delete all data in the database

When completed, this will be far from a robust or production-ready application, but we will, at minimum, learn how to view / add / delete data in our MongoDB database, using clean URLs in the browser.

Dependencies

In order to use the code in this article, you’ll need the following installed on your computer:

Node.js
MongoDB

Installation of these components is beyond the scope of this article, but if you follow the provided links, you will be pointed in the right direction.

File Structure

  • app.js
  • package.json

For this article, we will need two files: app.js and package.json. So, in your project folder, create these two empty files. The following sections will explain what to put in them.

Example # 1A

In Example # 1A, we have the contents of package.json. Note that for a more detailed discussion about package.json files you can search this blog for helpful articles. The two dependencies declared are “mongoose” and “express”. When you use node package manager to install dependencies, npm will download and install mongoose and express for us.

Example # 1B

In Example # 1B we see the command needed to install the dependencies for our application. Once you run this command, you will have everything needed to start writing code.

Getting Started

Open app.js in your text editor. From this point on, you can copy / paste the code in each example into the app.js (or you can scroll to the bottom of this page and paste the entire code listing in one step).

Example #2

In Example #2, we declare all of the top-level variables we’ll need in our script. Take note of “app”, which will be used to leverage the express middleware that we listed as a dependency. Also, “initApp”, which is called from the very end of this script. It is used to start the HTTP server.

Example #3

In Example #3, we have our database implementation. The details are identical to those in the previously mentioned article, so we’ll skip over that.

Example #4

In Example #4, we get into something new. If you remember from Example #2, the variable: “app” is an instance of the Express middleware object. We use the .get() method of that object to define what will happen when certain requests are made. When users navigate to the root of our web application, they are presented with a simple message. We accomplish this by passing two arguments to the .get() method: a string representing the requests we want to respond to (i.e. “/”), and an anonymous function. That anonymous function takes two arguments: “req” and “res”, which represent the request that was made, and the response object that we will send back. We use the .end() method of the response object, and pass in the string we want to send to the browser.

The second call to the app.get() method responds to “/json/delete”. It, in turn, calls a function named: utils.deleteAllData(), which will be explained a bit later.

Example #5

In Example #5, we use the app.get() method to respond to the request: “/json”. For this request, we want to show all of the data in the database. We start off by requesting all of the data in the database: salesMember.find({}).exec(). The anonymous function that is passed to the exec() method provides access to an error object (if there is one), and the results of our search. In this case, the result object is JSON, which contains all the data in the database, which we then stringify.

We then use the utils.isJsonCallback() method to determine if the user added a callback function name to the query string. If so, we wrap our database JSON with the named callback. We then deliver the JSON by passing it to the res.end() method.

Example #6

In Example #6, we respond to a request to add a new user to the database (i.e. “/addUser”). If you remember from the top of the script, the variable “url” allows us to leverage the same-named Node.js module, which provides programmatic access to the URL. We then use the “url” object to access the query string for the new user parameters. Once we have that information, we can leverage code that is nearly identical to the previous article, to create a new document in the collection. So just think of this as adding a row to a database table).

Once the new data has been saved, we then end the response with some HTML, informing the user of the successful data addition, and add a link that allows them to view all data or go to the home page.

Example #7

Example #7 contains all of the utility functions used throughout our code:

utils.isJsonCallback : Returns true if a callback name was provided in the query string
utils.getJsonCallbackName : Returns the name of the callback provided in the query string
utils.wrapDataInCallback : Returns the JSON data, wrapped in the callback function
utils.deleteAllData : Deletes all of the data in the database

Note: At the end of Example #7 you will also see a call to initApp(). This simply starts the HTTP server.

Example #8

So finally, in Example #8 we have the complete code for our working example. You can start the application by navigating to the root of the folder that contains app.js and entering the following command in the terminal: node app.js.

NOTE: On line # 97 of Example #8, I escape the double quotes that are part of HTML element attributes. I did this only because the color-coding of the plugin used to make code more readable was being particularly difficult for some reason. You will likely need to surround that entire string in single quotes, and remove the escape characters: “\”.

Summary

In this article we leverage MongoDB, mongoose and express middleware to create a very basic JSONP API. By using the .get() method of the express object instance, we created functions that respond to specific requests. As a result, we were able to provide the user with functionality to view all data, retrieve all data as a JSONP call, add a user to the database, or delete all data.