1

I have a route with a req.param of :groupIndex in it. I would like to process this index as middleware in order to get a specific id.

Node and express are new to me, so I'm possibly missing something simple but reading docs and looking at other implementations hasn't seemed to work.

Any idea where I might be going wrong?

// routes.js
const express = require("express");  
const router = express.Router();
const customMiddleware = ('./customMiddleware.js');
const db = require('./mysqlCon.js');

router.get('/person/:groupIndex(\\d+)', customMiddleware(), function (req, res) {

let id = req.params.id;
let query = `
            SELECT 
                *
            FROM 
                data
            WHERE 
                id = ?
        `;
        let query_params = [id];
        db.query(
            query, 
            query_params, 
            function(error, result, fields) {
                if ( result.length == 1 ) {
                    res.status(200).json( result[0] );
                } else {
                    res.status(401).json({});
                }
            }
        );
});





// customMiddleware.js
const db = require('./mysqlCon.js');

module.exports = (req, res, next) => {

    let groupIndex =  parseInt(req.params.groupIndex);
    let query = `
            SELECT 
                id
            FROM 
                listofids
            LIMIT 1 
            OFFSET ?
    `;
    let query_params = [groupIndex];
    db.query(
        query, 
        query_params, 
        function(error, result, fields) {
            if ( result.length == 1 ) {
                req.params.id = result[0].id;
            } else {
                res.status(401).json({});
            }
        }
    );
    next();
}

1 Answer 1

2

I would review the middleware guide, but generally all middleware functions have the following signature:

function myMiddleware(req, res, next)

Where req, res, next are passed in from Express itself. You do not invoke the function, you simply pass it in as an argument (higher-order functions) to your route definition:

router.get('/person/:groupIndex(\\d+)', myMiddleware, ...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.