Over the years I’ve used Express.js many times as a quick getting started example app. Since I often reference it I wanted to provide a short post that shows exactly what I do 99.9% of the time to start one of these quick Express.js reference apps. I’ve detailed in this post how to get started with Express.js the fastest way I know. There is one prerequisite, I’m assuming in this post you’ve already got Node.js installed. With that in mind, check out my installation suggestions for Node.js if you need to get that installed still. The other thing, is you’ll need to have git installed. On MacOS and Linux git is most likely installed already, if you’re on Windows I’ll leave that googling exercise up to you.
Create a directory and navigate into the directory.
mkdir quick-start-express cd quick-start-express
Now in that directory execute the following command. Note, this command is available as of node.js 8.2.0.
npx express-generator npm install
Inside that directory that you’ve navigated to, you’ll now have an Express.js skeleton app setup to run with the dependencies now downloaded with npm install. On MacOS or Linux run the following command to start the web app.
DEBUG=quick-start-express:* npm start
If you’re on Windows run the following command.
set DEBUG=quick-start-express:* & npm start
That’s it, one of the quickest ways to get a Node.js site up and running to start developing against!
If you’d like to dig in a bit deeper, here’s a great follow up post on creating APIs with Express. Give it a read, it’ll give you some great next steps to try out!
Even though it isn’t in the primary trunk of code for the ‘passport-http’ Passport.js Strategy, I’ve upgraded the packages.json and app.js file for the basic username and passport authentication to Express.js v4. If you’re using Express.js and are looking to migrate to v4 from v3 or earlier a great starting place is to check out the “Migrating from 3.x to 4.x” wiki page. As for the passport-http strategy, here’s the updated example I put together in a commit here with my own fork here, with the code changes below.
First step was to bump to the latest Express.js v4 Module. I did this with a simple edit to the packages.json file. The original looked like this
Technically the old file would have pulled the latest (which as of today I believe is 4.1.1) but it would also not do anything if you’d already pulled the example down. It just make sit more specific that the version is v4+ now.
After changing that dependency I added Morgan. Morgan is a replacement middleware for the logger. The final packages.json file looked like this when I was done.
Once that was done I nuked my node_modules directory and ran npm install to pull down the latest bits. Once I did that, starting with the app.js I made a few changes. Below is what the app.js file looked like when I started with.
function findByUsername(username, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.username === username) {
return fn(null, user);
}
}
return fn(null, null);
}
// Use the BasicStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
passport.use(new BasicStrategy({
},
function(username, password, done) {
// asynchronous verification, for effect…
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure. Otherwise, return the authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (user.password != password) { return done(null, false); }
return done(null, user);
})
});
}
));
var app = express.createServer();
// configure Express
app.configure(function() {
app.use(express.logger());
// Initialize Passport! Note: no need to use session middleware when each
// request carries authentication credentials, as is the case with HTTP Basic.
app.use(passport.initialize());
app.use(app.router);
app.use(express.static(__dirname + ‘/public’));
});
[sourcecode language=”javascript”]
var app = express.createServer();
// configure Express
app.configure(function() {
app.use(express.logger());
// Initialize Passport! Note: no need to use session middleware when each
// request carries authentication credentials, as is the case with HTTP Basic.
app.use(passport.initialize());
app.use(app.router);
app.use(express.static(__dirname + ‘/public’));
});
[/sourcecode]
I replace that with a nicely cleaned up Express.js v4 section of code and the replacement for logger, the morgan() library. Initializing passport however is still done in the same ole’ trusty way with initialize().
Ordering of code has changed a bit for express.js, which meant I needed to have the app.use commands before the following section, which I moved right up underneath the two app.use statements.
function findByUsername(username, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.username === username) {
return fn(null, user);
}
}
return fn(null, null);
}
// Use the BasicStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
passport.use(new BasicStrategy({
},
function(username, password, done) {
// asynchronous verification, for effect…
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure. Otherwise, return the authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (user.password != password) { return done(null, false); }
return done(null, user);
})
});
}
));
app.listen(3000);
[/sourcecode]
If you execute either of the curl commands shown in the comments in the app.js code you should see the respective response when running the application.
Time for the node.js “Deploy a Framework Friday”. First get node.js and express.js installed (i.e. npm install express) and then create your node.js application.
// Cloud Foundry Environment Variables
var port = (process.env.VMC_APP_PORT || 3000);
app.listen(port);
console.log("Cloud Foundry Demo Express server listening on port %d in %s mode.", app.address().port, app.settings.env);
[/sourcecode]
The emphasis is the port variable added for the VMC_APP_PORT. This variable is needed by the Cloud Foundry system to know which port that node will use to host on, which Cloud Foundry will then intelligently map to so you will get the standard default port 80 activity you expect. For more information about all this hosting mess with node.js check out one of my previous write ups on the topic on the New Relic Blog.
Once you’ve setup this file, then just deploy using the with npm support option that states the version of node.
At this point you should be able to navigate to http://localhost:3000 in a browser and view the default express.js web app. So now let’s add something relevant to the page. First, I’m just going to stick my name on the page in the index.jade file. My method for editing the file is usually to just use a text editor such as TextMate.
There isn’t really a whole lot to the file yet. One thing you’ll notice though, is the Jade Templating.
[sourcecode language=”vb”]
h1= title
p Welcome to #{title}
[/sourcecode]
This might seem strange at first, but here’s an example of the HTML mess we normally see and then the same thing cleaned up. So here’s the some HTML goo…
[sourcecode language=”vb”]
header.container#header
div.span-24#socialLinks
ul.right
li Follow us:
li
a(href=’http://www.twitter.com’)
| <img src="images/Twitter_32x32.png" alt="" />
li
a(href=’http://www.facebook.com’)
| <img src="images/Facebook_32x32.png" alt="" />
div.span-24#titleContent
div#textLogo
a(href=’/’, title=’GoldMind’)
span#companyName GoldMind
span#textLogoSubtitle What do you have to learn?
[/sourcecode]
Much shorter, much cleaner, and lots less noise when one yanks away all the repetitive chevrons. Now that we’ve looked at an example of nasty HTML and clean Jade, let’s step through how to get certain markup with Jade.
The first thing to note is that each tag is indented below the tag it is included within. That’s how things are nested in Jade, and intelligently, no closing tag is needed. But what if you need the id or class added to the tag. That’s also extremely easy. To add the id just add a hash between the tag and the id parameter like this.
If you open up the layout.jade file you’ll fine some other parts of the Jade Templating I haven’t covered, variables. In the layout.jade file you’ll find the following code.
[sourcecode language=”vb”]
!!!
html
head
title= title
link(rel=’stylesheet’, href=’/stylesheets/style.css’)
body!= body
[/sourcecode]
The title is set to title. Which is actually set in the index.js file. The index.js file has the routing functions that are called from the app.js file that launches the web application. Looking in the index.js file you’ll find the value that is passed in as the title. Change that to something custom for our app example. I changed mine as follows.
Also, to get a little closer to the HTML5 Spec, I changed the layout.jade page as follows.
[sourcecode language=”html”]
doctype 5
html(lang="en")
head
title= title
link(rel=’stylesheet’, href=’/stylesheets/style.css’)
body!= body
[/sourcecode]
With those two changes we should have a custom message that is processed and also HTML5 compliance. Be sure to kill node.js if it is still running and restart it so all the changes are taken into account.
Mashing it Up!
Now it is time to mash this CoderWall & Geekli.st stuff up, but alas, that’s coming in the NEXT blog entry. Stay tuned, I’ll have it up in the morning!
You must be logged in to post a comment.