Node Two

Middleware, Controllers, and Postman

Top Level Middleware?

Top level middleware is functionality that runs on every request received by your server.

 

The prime example of this is your JSON parser.

app.use(express.json())

When working with Express, top level middleware can be created by using the use( ) method, seen above.

Postman

Postman is an application that is used to test server endpoints.

 

To get started with Postman, use the link below to install it, then start the application and follow the set-up.

Using Postman

To use Postman, select the type of request (get, post, etc.) and then specify the URL for the request.

 

Hit send to see your results.

Using Postman

Postman also allows you to import collections.

 

Collections are a group of requests that allow you to test multiple endpoints at once.

 

You will use collections on your mini and afternoon projects today.

To use the collections, click import and select the 'postman_collection' file in your project directory.

 

Once imported, click on the runner button to open the test runner. Click 'Start Run' when you're ready to test your endpoints.

Using the Body

We do not need to make any changes to our endpoint to use the body object.

app.post('/api/users/')
app.post('/api/users', (req, res) => {
	//req.body = {
  	//first_name: "Andrew",
  	//last_name: "Westenskow",
  	//email: "andrew@email.com"
	//}
})

SELECT Body -> raw -> JSON

Note: Only post and put requests will send a body

Controllers

Controller files are a great place to separate logic from your server. (Remember the Modular Pattern?)

//controller.js
module.exports = {
  handlerFunc: (req, res) => {
    //functionality here
  }
}

module.exports allows our functions to be exported as an object

handler function

require controller

access function

//index.js
const ctrl = require('./controller.js');

app.get('/example', ctrl.handlerFunc)

Node 2

By Devmountain

Node 2

Controllers, Middleware, and Postman

  • 771