• Home
  • Portfolio
  • Articles
  • Pricing
  • About
  • Contact

Some things to know when starting with Express

Jun 28th, 2019

Alex Quasar

expressexpress overviewexpress summary

1. Middleware:

Middleware is blabh blah blah. To use middleware need use the use method.

Some examples of middleware are:

// Init MiddleWare for put and post requests. app.use(express.json({extended:false}));

2. Postman

For postman, for a post request you have many options on how to test your application.

One method is to use Body and Raw and JSON(application/json) to test sending an request and response in your application.

Inside the postman body for example...

{ "username":"Alex", "email":"" }

3. Express-validator

It is crucial that you validate the data you collect in your app. There is a lot of different ways to do validation, but I think express-validator provides a clean and concise way to do validations in your app.

Example: Here is a simple validation route for when a user registers. It includes there name, email and password. The code is fairly self explanatory and you can check the results are working with Postman!

You can quickly get started by installing the express-validator package.

npm i express-validator

Once that is set up include the package in your relevant route file. Since we are registering users I will add the following in the users.js file under the routes/api folder.

const { check, validationResult } = require('express-validator');

Here, validationResult will be called later on the code and req object containing the name, email and password will be passed into it. If all the checks pass, then errors will be an empty object. Otherwise we can return an errors array. As shown below, check will have different methods such as isEmail and withMessage that checks whether the req ( user input ) is a email. If it fails to pass the isEmail check, than withMessage will be called and the custom, specified error message will be shown.

See full example.

// route:       GET api/users
// description: Register a user
// access     : Public
        check('name','Name is required').not().isEmpty(),
            .withMessage('Please enter a valid email'),
        check('password','Please enter a password 8 characters or more')
                .withMessage('Password must be between 8 and 25 characters!')
                .matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, 'i')
                .withMessage('Password must include one lowercase character, one uppercase character, a number, and a special character.')
    async (req,res)=> {
        const errors = validationResult(req);
            return res.status(400).json({errors: errors.array()})
        try {
            res.json({msg:'user is working!'})
        } catch (error) {
            res.status(500).send('server error');

We can make our validation as customized as desired as the matches method allows us to pass in regular expressions. This rather complicated regular expression is used to check a password matches the following requirements in the message. For more on regular expressions visit my article here.

4. Creating a 404 not found route

Express tries to find the routes in the order they are executed. If it cannot find a matching route, than the response will time out. To avoid that we can add a `404 not found` route after all the routes are defined.

 // 404 route
app.all('*', ( req, res, next ) => {
  res.status(404).json({msg:`Requested route: ${req.originalUrl} not found!`})

5. Global Error Handling

If we pass an argument into the next() middleware, express assumes that argument is going to be an error. argument. We can improve error handling, by calling next(error) in the catch block like so:'/', auth, async (req, res, next) => {
        try {
            const user = await User.findById('-password');
                res.json({msg: 'Access denied'});
            // create new tour from the req.body.
            const tour = await Tour.create(req.body);
        } catch (error) {

An example:

Lets take an example