Install Express.js

Firstly, you have to install the express framework globally to create web application using Node terminal. Use the following command to install express framework globally.

snippet
npm install -g express
SettingServerExpressJS

Installing Express

Use the following command to install express:

snippet
npm install express --save
SettingServerExpressJS

The above command install express in node_module directory and create a directory named express inside the node_module. You should install some other important modules along with express. Following is the list:

  • body-parser: This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser: It is used to parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer: This is a node.js middleware for handling multipart/form-data.
snippet
npm install body-parser --save
SettingServerExpressJS
snippet
npm install cookie-parser --save
SettingServerExpressJS
snippet
npm install multer --save
SettingServerExpressJS

Express.js App Example

Let's take a simple Express app example which starts a server and listen on a local port. It only responds to homepage. For every other path, it will respond with a 404 Not Found error.

snippet
File: express_example.js
snippet
var express = require('express');
var app = express();
app.get('/', function (req, res) {
   res.send('Welcome to rookienerd');
})
var server = app.listen(8000, function () {
var host = server.address().address
  var port = server.address().port
 console.log("Example app listening at http://%s:%s", host, port)
})
SettingServerExpressJS

Open http://127.0.0.1:8000/ in your browser to see the result.

SettingServerExpressJS
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +