Development

Local Development with Node and Express

Create your Server

If you are working with React and webpack, you probably or mostly never have to create your own local server. If you ever wonder how it works under the hood, here is a simple way to get a local server up and running in no time.

Install Node

First we need Node. You probably have node installed. If not, and you’re on a Mac use Homebrew:

Your First Server

Create a index.js file:

Then on our index.js :

To learn more about the Node http package, use the following link to learn all about http.

Finally, run index.js with:

Go to your browser and enter http://localhost:3000/ in your browser. You should see the text, ‘Hello Node.js.’

Request and Response

To have different responses based on different URLs, we now change our respond:

Let’s restart Node: CTRL + C. Run  node index.js. Go to localhost:3000 and navigate the routes:

To see your request information, open developer tools/network/status. It will show the status code from the request.

What about adding HTML Files to our routes? In the same directory of index.js, create:

With Emmet, it is as easy as typing ! or doc and hit the ENTER KEY. Your file will have the HTML code necessary to run. If you use Visual Code like me, support for Emmet snippets and expansion is built right into Visual Studio Code; no extension required.

Emmet takes the snippets idea to a whole new level. You can type CSS-like expressions that can be dynamically parsed, and produce output depending on what you type in the abbreviation. Emmet is developed and optimized for web developers whose workflow depends on HTML/XML and CSS but can be used with programming languages too. Bookmark this: Emmet Cheat Sheet.

Now, add a navigation. Let’s use Emmet one more time.

Between the body tags, go ahead and type ul>li*3>a and hit enter. This will create an unordered list with three items and a tags. Add your links, as seen in this screenshot, and then add a h1 tag on each of the pages named Homepage, About, Contact, and Page Not Found. Your files should look like this:

Let’s update index.js.

Restart the server with CTRL + C and run  node index.js . Go to: http://localhost:3000; you’re now navigating your HTML files.

 

Express

Express is a minimal and flexible NodeJS web application framework that provides a robust set of features for web and mobile applications. Express provides a layer of abstraction to make handling web traffic and APIs easier. In short, Express did for NodeJS what Bootstrap did for HTML/CSS and responsive web design.

Some of the advantages of using Express are:

  • Almost the standard for Node.js web middleware
  • Simple, minimalistic, flexible, and scalable
  • Fast app development
  • Fully customizable
  • Low learning curve
  • Majorly focused on browsers, making templating and rendering an almost out-of-the-box feature

Before we install Express, we need to create a package.json file. On your root directory, run:

If you’re not familiar with npm init and its flags, I recommend running npm help init for definitive documentation on these fields and exactly what they do.

Now that we have our package.json in our project. Let’s go ahead and install Express:

Let’s refactor our index.js to work with Express:

Previously we create a server and started with:

We have to take care of importing http, fs , other packages, and also the request and response object; but with Express, we achieve the same thing.

Run CTRL + C and  node index.js . Check your terminal. It should now log from Express, your routes are probably broken.  We’ll take care of that next.

Routing with Express

You define routing using methods of the Express app object that correspond to HTTP methods—for example, app.get() to handle GET requests and app.post() to handle POST requests.

The following code is an example of a very basic route.

To learn more about Express routing click here. For now, let’s add routing to our app go to index.js.

Express adds things like the sendFile method which makes it easier to write request handler functions.

That’s it! Run CTRL + C and node index.js and navigate within your app.

 

Serving Static Files

Express has this special function, app.use(), which mounts the specified middleware function or functions at the specified path. The middleware function is executed when the base of the requested path matches path. This special function, express.static(), is a built-in middleware function in Express. It serves static files and is based on serve-static.

What is middleware? Middleware is a software that bridges gaps between other applications, tools, and databases in order to provide unified services to users. It is commonly characterized as the glue that connects different software platforms and devices together.

Create a directory:

Add this code on your index.js file in the root of your app:

To reference styles.css in index.html, add in index.html and on all your HTML files between the <head> in the following lines:

Let’s make sure we are reading the styles and script; on your style.css add:

In your index.js, be sure that this is the new index.js the one on our public folder on the js directory, and is not our root index.js.

That’s it! You have an app running locally with Node and Express.

We learned how to install and run a Node application locally and leverage it with Express. We also learned how to serve static files with express.static().

Automatic Server Restart with Nodemon

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server, making it perfect for development. We have been starting and stopping our server each time we make a change on index.js, but with Nodemon, we don’t have to that anymore.

Let’s install Nodemon: npm i nodemon --save-dev. Now update your package.json.

So instead of node index.js, we now run our app with npm start.

I hope this article helps you understand what happens under the hood on some of the most popular JavaScript bundlers.

Comments

Have a comment?

Your email address will not be published.

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupportunifiedupdatesvaultwebsitewordpress