Express Overview
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework −
- Allows to set up middlewares to respond to HTTP Requests.
- Defines a routing table which is used to perform different actions based on HTTP Method and URL.
- Allows to dynamically render HTML Pages based on passing arguments to templates.
Installing Express
Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal.
$ npm install express --save
The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express −
- body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
- cookie-parser − 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.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
Routing
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
app.get(/a/, function (req, res) {//any url contains a
res.send('/a/')
})
app.get('/name/:name',function (req,res){//req.params={name:"mohammed"}
res.send("hello world");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
})
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})
static files
Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this −
app.use(express.static('public'));
upload file
var bodyParser = require('body-parser');
var multer = require('multer');
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null,config.filesUploadPath);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
let uploadFile = multer({
storage: storage,
limits: { fileSize: config.fileMaxSize }
}).single(config.fileQueryName);
const UploadFile = [uploadFile,async (req, res) => {
try {
let file=req[config.fileQueryName];
fs.renameSync(file.destination+file.originalname,newName);
} catch (err) {
}
}];
cookies management
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)
middleware
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])//multiple response
let config=require("./config");
let express=require("express");
let app=express();
app.use(function(req,res,next){
console.log("middleware");
next();
});
app.get('/name',function (req,res){
res.send(req.query);
});
let server=app.listen(config.port,()=>{
console.log(server);
});
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Content-Type: application/json
app.use(express.json())
Content-Type: application/x-www-form-urlencoded
app.use(express.urlencoded({
extended: true
}))
and you can acess to it by
req.body.fieldName;
raw data
const express=require("express");
const bodyParser = require('body-parser');
let options = {
inflate: true,
limit: '100kb',
type: 'text/plain'
};
let app=express();
app.use(bodyParser.raw(options));
app.post("/hello",(req,res)=>{
res.send(req.body);//body is string if type: 'text/*' else buffer
})
app.listen(8081,()=>{});
HTTP headers
app.get('/', (req, res) => {
console.log(req.headers)
})
app.get('/', (req, res) => {
req.header('User-Agent')
req.get('User-Agent');
})
Response Methods And Properties
The methods on the response object (res
) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
Method | Description |
---|---|
res.download() | Prompt a file to be downloaded. |
res.end() | End the response process. |
res.json() | Send a JSON response. |
res.jsonp() | Send a JSON response with JSONP support. |
res.redirect() | Redirect a request. |
res.render() | Render a view template. |
res.send() | Send a response of various types. |
res.sendFile() | Send a file as an octet stream. |
res.sendStatus(), res.status(code) | Set the response status code and send its string representation as the response body. |
res.app | hold express app |
res.cookie() res.clearCookie() | res.cookie(name, value [, options]) |
res.set('Content-Type', 'text/html')
res.type('.html')
// => 'text/html'
res.type('html')
// => 'text/html'
res.type('json')
// => 'application/json'
res.type('application/json')
// => 'application/json'
res.type('png')
// => image/png:
for more visit this link