Home > front end >  Nodejs express app fails when using middleware on route
Nodejs express app fails when using middleware on route

Time:01-15

I am getting error Property 'admin' does not exist on type 'Request<{}, any, any, ParsedQs, Record<string, any>>'. Also nodejs app will not run as it fails with the same error. I am using typescript enter image description here

app.get('/users', auth, (req, res) => {
    console.log(` User is admin = ${req.admin}`);
    console.log('Users Page');
    res.send('Users Page');
});

function auth(req, res, next) {
    if (req.query.admin === 'true') {
        req.admin = true;
        next();
    } else {
        res.send('No auth');
    }
}

CodePudding user response:

Make also sure that you properly structure the URL something like this http://localhost:3000/users?admin=true

import { NextFunction, Request, Response } from 'express';


app.get('/users', auth, (req: Request, res: Response) => {
    console.log(` User is admin = ${req.admin}`);
    console.log('Users Page');
    res.send('Users Page');
});


declare module 'express-serve-static-core' {
  export interface Request {
    admin: boolean;
  }
}

function auth(
req: Request<{}, {}, {}, {admin: boolean}>,
res: Response, 
next: NextFunction) {
    if (req.query.admin === 'true') {
        req.admin = true;
        next();
    } else {
        res.send('No auth');
    }
}
  • Related