Node Js Express Server
Express.js is a web application framework for Node.js. Express.js is based on the Node.js middleware module called connect which in turn uses http module.
Core Features of express:
- Set up middleware for handling HTTP requests.
- Routing tables’ setup for performing actions based on urls.
- Render HTML pages
Why Express Js when we have http?
This is a very common question asked by developers why they need to use express framework when they can do the same things with http module.
Well, HTTP module is just a simple built-in module to handle basic http calls, however, express js is built on top of http to provide more functionalities when it comes to a web application. Express takes care of basic repeated tasks that are required for an web application. Tasks like, parsing the body of the request, parsing cookies are very much required for every web-application and which Express provides by default.
Installing Express Js
Since express js is not part of node built in modules, we need to install it by ourselves.
Let’s install it
For global installation :
npm install -g express
For local/project installation
npm install express –save
This will also update package.json and install a copy local to your folder.
Libraries commonly used along express js:
- body-parser – handling request body
- cookie-parser – handling cookies
- multer – Handling files/ multi-part objects.
Let’s start with sample codes using express.
Create a simple web handler and print data on browser
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Welcome to Learn Jobisite');
})
var server = app.listen(8081, function () {
console.log("Example app listening at https://localhost:8081/")
})
On running this
Browser display : Welcome to Learn Jobisite
Browser display : Cannot GET /dd
Let’s understand the statements
For using express, we need to import express framework and assign app to this express.
var express = require(‘express’);
var app = express();
Now define a handler for url. A call with url host:port/ will trigger call to the below function which accepts request and response variables.
app.get(‘/’, function (req, res) {
res.send(‘Welcome to Learn Jobisite’);
})
Now we need to create and run this application on the server
var server = app.listen(8081, function () {
console.log(“Example app listening at https://localhost:8081/”)
})
Methods available in Request and Response
Request | Response |
accepts()
acceptsCharsets() acceptsEncodings() acceptsLanguages() get() is() param() range() |
append()
attachment() cookie() clearCookie() download() end() format() get() json() jsonp() links() location() redirect() render() send() sendFile() sendStatus() set() status() type() vary() |
The basic concept of Route in Express
app.METHOD(path, handler)
Here app is the instance of express module in application. Method refers to the HTTP method type, like GET, POST, PATCH etc ; path refers to the url path of web application and handler refers to the handling code for the given path.
Create a sample application using express with form submit.
Here we will ask a user to submit their name, username, and password and then save it into a file and show them another page.
Let’s start with register html page.
<html>
<body>
<h3> Register </h3>
<form action = "http://localhost:8081/registerSave" method = "POST">
Name: <input type = "text" name = "fname"> <br>
User Name: <input type = "text" name = "username"><br>
Password: <input type = "password" name = "password">
<input type = "submit" value = "Register">
</form>
</body>
</html>
Now create javascript file to create server and handle requests
var express = require('express');
var fs = require('fs');
var bodyParser= require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/register', function (req, res) {
res.sendFile(__dirname + "/" + "register.html" );
})
app.post('/registerSave', function (req, res) {
console.log('User submitted registeration form');
let name =req.body.fname;
let username =req.body.username;
let password =req.body.password;
let data='\n'+username+'|'+password+'|'+name;
//Save the data in file.
fs.appendFile('c:/test/users.txt',data, function (err) {
if (err) throw err;
console.log('Data Saved!');
});
res.send("Your data is saved")
})
var server = app.listen(8081, function () {
console.log("Example app listening at https://localhost:8081/")
})
Now run the application.
c:\test>node example8.js
Example app listening at https://localhost:8081/
On Submit of Register button, it will save the data into file.
Note: we need to use body-parser for getting/parsing post data .
We can use
app.use(bodyParser.urlencoded({ extended: false })); // url encoded data objects
or
app.use(bodyParser.json({ extended: false })); // to get json object
Create a sample application to upload files.
Here we will be using multer to upload and save file to the system
Let’s create upload html file for users to upload any file
<html>
<body>
<h3> Upload </h3>
<form action = "http://127.0.0.1:8081/uploadsave" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="file" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
Now let’s create a server to listen and upload files.
var express = require('express');
var fs = require('fs');
var bodyParser= require('body-parser');
var multer = require('multer');
var app = express();
app.use(bodyParser.urlencoded({extended: true}))
//app.use(multer({dest:'c:/test/'}).single('file'));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'c:/test/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({storage: storage})
app.get('/upload', function (req, res) {
res.sendFile(__dirname + "/" + "upload.html" );
})
app.post('/uploadsave', upload.single('file'), (req, res) => {
try {
res.send(req.file);
}catch(err) {
res.send(400);
}
});
var server = app.listen(8081, function () {
console.log("Example app listening at https://localhost:8081/")
})
Now let’s run the application
c:\test>node example8.js
Example app listening at https://localhost:8081/
Go to the browser and upload the file
On click of upload , it will be saved to the disk.
Frequently Asked Questions
How express-cookie session helps in XSS attacks?
XSS attacks are seen when attacker injects some executable javascript code which can set/update cookies into any of the html pages. On page rendering, these javascript elements executes and changes cookie values.
To avoid this , we can set some attributes, like HttpOnly, which means cookies can not be accessed by javascript and secure attribute, which means that the request sent over https.
express-cookie session offer this feature by default.
What are the steps for setting up an Express JS application?
Following are the steps for an Express JS application –
– Create A folder with project name
– Create a file named package.json in the folder.
– run ‘npm install’
– Router file is made within the package that consists of a folder named index.js.
– App is made within the package that has the index.html file.
How can we add cors in express js?
We need to add cors details in server.js file.
For Example –
app.all(‘*’, function(req, res, next) {
res.set(‘Access-Control-Allow-Origin’, ‘*’);
res.set(‘Access-Control-Allow-Methods’, ‘GET, POST, DELETE, PUT’);
res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);
if (‘OPTIONS’ == req.method) return res.send(200);
next();
});
What is the use of next in Express JS?
It passes management to a consecutive matching route.
What is Scaffolding in Express.js?
Express js uses Scaffolding to create skeleton structure of the application.
Using Express application generator
npm install express-generator -g
express myExpressApp
It will create express application ‘myExpressApp’ with following files
bin:The bin folder have one file called www
public:Public folder to have JavaScript, CSS, images etc.
routes: Routes folder to have routing files.
views: View folder to have view files of the application.
app.js: The app.js file is the main file of the application.