Tuesday, 5 March 2019

Express: Exploring request object


‘request’ object represents a http request that can hold all the query parameters, route parameters, request headers, and request payload etc.,

index.js
//Load express module
const express = require('express')

//Put new Express application inside app variable
const app = express()

const port = 3000

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/welcome/:userName', (req, res) => {
 res.send(`Welcome Mr.${req.params.userName}`)
})


// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js.


Open the url ‘http://localhost:3000/welcome/krishna’ in browser, you can see below kind of response.


req.app: Get the reference of express application
req.baseUrl: Return the url path on which this router instance is mounted
req.originalUrl: Return original request url
req.path: return the path part of the url
req.body: Get the request payload
req.cookies: Get the cookies associated with this request
req.method: Get the http method of the request
req.params: Get route parameters
req.protocol: Get the request protocol: http or https
req.query: Get the query parameters
req.route: Get currently matched route
req.secure: Tells about secure connection
req.accepts(types): Check whether given content types are accepted by client or not
req.acceptsCharsets(charset [, ...]): Return the accepted char sets of the client.
req.acceptsEncodings(encoding [, ...]): Get the accepted encodings by client
req.acceptsLanguages(lang [, ...]): Return the accepted language by client
req.get(field): Access http request headers
req.is(type): Check the matching content type
req.param(name [, defaultValue]): Return value of the parameter

Previous                                                 Next                                                 Home

No comments:

Post a Comment