Create a Basic Server with Express

Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

In this lesson we will initialize our Express application using npm init.

After loading express through npm we will look at a couple basic functions Express exposes to us such as .get and .send. This will allow basic interaction via the url.

We will also see how using a package like nodemon can allow for rapid iteration when developing an application.

[00:00] Since Express is a Node program, we're going to start by initializing a package JSON with our default values by just using MPMinit-y.

[00:08] We can install the Express and we use the -S flag so that it gets saved to our package.json, and we have that dependency recorded. We're going to create an index.js file, and then we will go look at that and see how we initialize our Express application.

[00:28] If we require Express here, that's going to actually give us a function reference. To create our app instance, we're just going to call that function Express with a parentheses, and now we have an instance of an Express app.

[00:46] The most basic call here is going to be App.Get, with just a slash, so that's essentially saying, "Express, when you get an HTTP Get request to the root path, we want you to call this function that we are going to give you."

[01:02] You'll see that the two arguments that we pass in are Req and Res, or Request and Result. Basically, to send data back to the browser or whoever is calling this, we're just going to say Result.Send, "Hello World," and then we're going to start our application by telling it to run on port 3,000.

[01:24] If we now go back to our terminal and start up index.js, we can see that we can go in our browser, load up localhost 3,000 and we do in fact get, "Hello World" returned. It would be nice to have a little bit of feedback in the terminal, usually, when you start that server so that you know what's going on.

[01:42] We are going to create a server variable, and then we're going to give it a callback function when we call, listen so that we can know when that server is starting up. In this case, we are going to just log out a message saying, "Hey, there's a server running at..." whatever port it is that we are starting up on.

[02:01] If we save that, and then go back to our terminal, we can kill the server that was still running, and then restart it, and we now see our message that tells us that our server is in fact running on port 3,000.

[02:14] One thing that is a best practice or at least a convention in the node ecosystem is that, when you're dealing with a server application, you're generally going to want to create a MPM start command that will start up your server.

[02:28] That way, people don't have to know which file it is that gets used, any possible arguments that are involved. We are going to create an MPM start script here in our package.JSON, and now we can call it MPM start. You can see that it is in fact just calling node index.js, and that gets our server running just the same as before.

[02:49] We can go ahead and kill that, and you will notice that every time we make a change, and we want to restart things that we have to kill that server. During development, that can get really annoying, really fast. What we're going to do is we're going to install a package called NodeMon, which will essentially lead us set up a file watch so that when any of the files in our project change, it's going to restart that server.

[03:17] While that's installing, we're going to set up a dev MPM script that just runs NodeMon and passes it the index.js file. Now we can run MPM run dev, and it's going to run that NodeMon call and start up our server. You can now see that if we go and change our file, and save that, you get the server restarting automatically in the terminal.

[03:43] This makes it a whole lot easier to work and be productive as you are trying things out, and developing. Now, we can go back and make changes at will, and not have to worry about restarting that server in between each time. And so, just to show the next most basic thing in Express, we can tell it, when you get a HTTP Get request to the /yo path, we want you to call this handler instead of the other one, and we're just going to send back, "Yo."

[04:16] Our server restarted automatically for us. We can go try out that URL, and so we do in fact get a different response.

flied onion
flied onion
~ 9 years ago

I think, "res" (the second argument of callback function) is "response", not "result".

Response methods

Nick
Nick
~ 9 years ago

Very well done...but, am I the only one bothered by the choice not to use idiomatic JavaScript? Not using semi-colons is fine when it's your personal code, but why abandon the standard when teaching or collaborating with others? Nobody will argue the benefit of choosing a style that suits us individually when we are working for ourselves (I certainly do), but not using an idiomatic style makes others work needlessly harder to follow. That makes your course content less effective.

The cliche is worth repeating. Coding standards exist for the purpose of working with others. If we all worked alone, we wouldn't need stye guides.

One reason for the popularity of Express is how truly readable the source is. Similarly, a reason for the popularity of Node is that the community bought strongly in to a common coding style, which has led to higher readability of npm modules. I think that by not following suit, this series is weaker. https://github.com/felixge/node-style-guide

That said, the content is still excellent!

Ben Clinkinbeard
Ben Clinkinbeardinstructor
~ 9 years ago

You're absolutely right. I misspoke and it slipped through in the edit process, sorry about that. Thankfully, there was only one instance where I did that and I say response everywhere else in the series.

Ben Clinkinbeard
Ben Clinkinbeardinstructor
~ 9 years ago

Hi Nick, thanks and I'm glad you enjoyed the series.

I'm also sorry you find the lack of semicolons distracting. I personally go back and forth on the issue, but don't feel strongly either way. I've recently been omitting them, partially because I switched to Atom and the standard-linter and standard-fixer packages were the best combo I found for painlessly keeping files formatted.

I think the point that resonates with me the most on the issue is that the rules for when you NEED semicolons is much simpler than when you don't. The only time they are 100% required is when starting a line with ( or [, which is extremely rare. (With the possible exception of IIFEs.)

While using semicolons is certainly more popular than not using them, I don't think I'd consider it non-idiomatic. It's just a stylistic choice, though I did get a good laugh when the repo you linked to referred to a HN thread as scientific proof. :) I think http://standardjs.com/rules.html#automatic-semicolon-insertion-asi- makes some good points, and the video linked there expands a bit on how the rules get a bit murkier when using semicolons.

All of that said, I do appreciate your feedback. I debated on whether or not to use that style for the videos, and if I get more feedback that it's distracting I may change course in the future.

Thanks for watching, Ben

Nick
Nick
~ 9 years ago

Ben, Ok, I get it. You write code for yourself :--)

But, semi-colons are considered "idiomatic" because they are defined as such by the inventors of the language and by every known style guide, save the recently introduced and misnomer'ed "JavaScript standard". But you miss a larger point.

Not using semi-colons is NOT merely a matter of style, but a conscious decision to write buggier code. That advice has been stressed repeatedly over the years by both Douglas Rockford (see below) and JavaScript creator Brendan Eich, who says that relying on Automatic Semicolon Insertion (ASI) is "reckless". In other words, semicolons are considered "idiomatic" because they are a consensus "best practice".

Bugs that would be avoided with the use of the semi-colon are some of the nastiest to find. I've got a co-worker who only recently agreed to use semi-colons when the team wasted 4 hours tracking down a bug of his that would have been avoided with a semi-colon. Being an old guy (ouch), I've seen this movie before. Experiments with the unconventional ends as the pain of unnecessary bugs always trumps stylistic preference.

You're setting an example for your students, many of whom are new to JavaScript. I think this should be their guidance:

  1. Google JavaScript Style Guide http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Semicolons

"Always use semicolons. Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that."

The Google guide also describes the dangers of not using semi-colons.

  1. Rockford's definite Code Conventions for the JavaScript Programming Language http://javascript.crockford.com/code.html Put a ; (semicolon) at the end of every simple statement. Note that an assignment statement that is assigning a function literal or object literal is still an assignment statement and must end with a semicolon. JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of semicolon insertion.

  2. jQuery Style Guide https://contribute.jquery.org/style-guide/js/ "Semicolons Use them. Never rely on ASI."

  3. AirBnB Style Guide. https://github.com/airbnb/javascript "Semicolons • Yup"

Finally, the collaboration from 20+ leading JS practitioners that endeavors to define "idiomatic": 5) idiomatic.js https://github.com/rwaldron/idiomatic.js "We do not intend to impose my style preferences on other people's code or projects; if an existing common style exists, it should be respected."

"Arguments over style are pointless. There should be a style guide, and you should follow it" Rebecca Murphey   "Part of being a good steward to a successful project is realizing that writing code for yourself is a Bad Idea™. If thousands of people are using your code, then write your code for maximum clarity, not your personal preference of how to get clever within the spec." Idan Gazit

Jack
Jack
~ 8 years ago

Sir, aren't we supposed to pronounce nodemon like we pronounce pokemon ;)? Thanks for the lesson.

Tony Kung
Tony Kung
~ 8 years ago

I got an error message in my terminal when I type in node index.js

module.js:442 throw err; ^

brinka
brinka
~ 8 years ago

Thank for the lesson. I am a nebbie, what does '-y' means in npm init -y ?

Ben Clinkinbeard
Ben Clinkinbeardinstructor
~ 8 years ago

Hi Brinka,

npm init by itself will ask you a series of questions to determine how to populate the package.json file it creates. -y, as well as --yes, -f, and --force, tell npm to use the values defined in your ~/.npmrc file and skip the questions.

Ben

Ningze
Ningze
~ 8 years ago

what is the atom theme you are using in the video?

Ben Clinkinbeard
Ben Clinkinbeardinstructor
~ 8 years ago

Hi Ningze,

I think that was a slightly modified version of Tomorrow Night Eighties. These days I'm using Oceanic Next, which is similar.

Cheers! Ben

bradwoods.io
bradwoods.io
~ 7 years ago

How come we need to use 'run' when start nodemon but not when using 'npm start'?

Ben Clinkinbeard
Ben Clinkinbeardinstructor
~ 7 years ago

Hey Brad, support for some scripts, like start and test, is built into npm. https://docs.npmjs.com/misc/scripts

To run custom scripts you have to pretend run to the name. https://docs.npmjs.com/cli/run-script

Belajar Bebas Bisa
Belajar Bebas Bisa
~ 4 years ago

Hi Ben, How to change PORT in express generator that it has already gived default to 3000 ? Im Stuck.., please Help

Markdown supported.
Become a member to join the discussionEnroll Today