A demo app for Express
A demo app for express
git clone https://github.com/imranhsayed/express-app
git checkout branch-name
- Middlewares are functions added to the stack, that have access to the request and response object.
- They are executed sequentially. We can do things like validation, authentication, data-parsing etc inside of each middleware.
- When the request comes in it passes through each of the middleware, before reaching the actual route.
- An express application is a stack of middleware running one after the other.
- The
next()
must be called at the end of every middleware ( function ), to move the processing to the next middleware in the stack.
- The
body-parser
middleware parses the form data, so that we can read it.- Calling this function and setting extended to false,
bodyParser.urlencoded( {extended: false} )
forces the use of node's native queryString module, which parses the data . It returns a middleware function that parses data.
const bodyParser = require( 'body-parser');
app.use( bodyParser.urlencoded( {extended: false} ) );
response.sendStatus( 200 )
is used in our express routes, when we don't want to send a body along with the response./posts
, we can chain them together using app.route()
like so: app.route( '/posts' )
.get( ( req, res ) => ... )
.post( ( req, res ) => ... )
app.route( $path )
takes the route path and returns a route object that handles all request to the given $path
const router = express.Router();
and export router at the bottomrouter.get()
, or chain them using router.route()
/
is relative to where this router will be mounted in your main entry point file server.js
const express = require( 'express' );
const router = express.Router();
router.route( '/' )
.all( (req, res) => ... )
.get( (req, res) => ... )
.post( (req, res) => ... );
router.get( '/:id', ( req, res ) => ... );
module.exports = router;
router.all()
is used for all types of routes ( get, post, delete etc ) to that url.routes/post.js
into our main entry point file server.js
const posts = require( '/routes/posts' );
app.use( '/posts', posts );
// server.js
const express = require( 'express' );
const app = express();
const port = 3000;
const products = require( './routes/api/products' );
app.use( '/api/products', products );
app.listen( port => console.warn( `Ready on http://localhost:${port}` );
// routes/api/products.js
const express = require( 'express' );
const router = express.Router();
router.get( '/getProducts', ( req, res ) => ... );
module.exports = router;
The
express.static()
middleware that comes shipped with express, automatically servers theindex.html
on root url'/'
without having to create a route usingapp.get( '/' )
app.use( express.static( 'public' ) )
- Creates a custom middleware called loggerMiddleWare.
- Run
npm run dev
- Open browser at
http://localhost:5000
- Every time you refresh the page, a GET request to
http://localhost:5000/
is made
and the middleware intercepts that request and when the response for that request is finished
it calculates the time it took for that request to complete and prints that.
- Also adds the message to a
log.txt
file
- An example to create a route and get the post data at
/posts
- If the user adds a query string
?limit=2
in the route, then it should return those many post items
- An example to create a dynamic route at
/posts/:name
- Request to
/post/movies
will return 'I love movie blogs'- Request to
/post/software
will return 'I like Express'- Request to name that's not available in post object, like
/posts/xyz
will return 'No description found for xyz'
const posts = {
'movies': 'I love movie blogs',
'games': 'The best game of the year is God of War 4',
'software': 'I like Express'
};
// Dynamic Route
app.get( '/posts/:name', ( req, res ) => {
const description = posts[ req.params.name ];
// If the value of 'name' passed in the route does not exist as posts property
if ( ! description ) {
res.status( 404 ).json( `No description found for ${req.params.name}` );
} else {
res.json( description );
}
} );
npm run dev
Starts Node server at http://localhost:5000