Node Two

Top Level Middleware and Controllers

Top Level Middleware?

Top level middleware is functionality that runs on every request to 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.

What is CORS?

CORS stands for Cross Origin Resource Sharing, and simply means other 'origins' (other servers and client sides) can communicate with your own server. By default, your Node/Express doesn't allow CORS, but we can allow it by installing the 'cors' package from NPM.

npm install cors

Once installed, require it to the top of your server and then invoke it as top level middleware.

const express = require('express')
//require cors
const cors = require('cors')

const app = express()

//top level middleware
app.use(cors())

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 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 this on your mini and afternoon projects today!

Click import and select the 'postman_collection' folder sitting 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.

Controllers

Controller files are a great practice for separating your server code into more modular chunks. The main purpose of handler functions is to house your endpoints handler functions.

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

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

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

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

handler function

require controller

access function

Node Two

By Matthew Bodily

Node Two

  • 201