user68288
user68288

Reputation: 784

How can I write a route in express to perform middleware validation and then return data to user?

My goal is to have angular make a call to an Express API. The API will then use middleware to validate a token from the request header. If the token passes I want it to then run a function performs the intended GET and returns data from the database.

const express = require('express');
const router = new express.Router();

// Middleware that will return a status of 200 if sucessful
var authMiddleware = require('../middleware/AuthMiddleware.js');

// Controller that calls the db_api file which queries the DB
const o_l_vfn = require('../controllers/o_l_vfn.js');

// What I am doing currently that is not working
router.get('/o_l_vfn', authMiddleware.Validate, o_l_vfn.get);


//Currently getting an error of: 
// ERROR FOUND o_l_vfn: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

module.exports = router;

Upvotes: 0

Views: 2892

Answers (2)

Muhand Jumah
Muhand Jumah

Reputation: 1958

Refer to this for a guide on how to write express middlwares https://expressjs.com/en/guide/writing-middleware.html it is a really good guide and should be very helpful.

Here is the short answer though, writting a middleware is simple. Here is an example:

function authMiddleware(req, res, next) {
      // Write your logic here
      console.log('This is a middleware!!!')
      next()
}

now in your express app do something like this

...

app.use(authMiddleware)
...

The above snippet will run your code before every route, if you would like to write this only before a specific route then do something similar to the following

app.get('/', authMiddleware, (req, res) => {
    // Run your endpoint logic here
    res.status(200).end()
})

Middlewares should never ever return a successful status! In your code it says

// Middleware that will return a status of 200 if sucessful

This is wrong, middlewares are like waterfall, they will do something but SHOULD NOT return a status except an invalid status, if everything successful they should call next() so the next function can run in your case it is the controller. In case of an invalid state such as invalid token then your middleware should return a some sort of status code such as 400.

Upvotes: 1

pspi
pspi

Reputation: 11947

A better way to express your validation middleware logic is to let it pass to next() if the auth token is valid. Or, prematurely stop processing and respond with 401 Unauthorized if the auth token is not ok.

Now you're getting into trouble responding twice: first in the auth middleware and then in the controller. If you follow the suggested logic, the server responds only once in both happy path and unauthorized scenarios.

Upvotes: 1

Related Questions