在路由上使用中间件时,Nodejs Express应用程序失败

z4iuyo4d  于 2023-01-16  发布在  Node.js
关注(0)|答案(1)|浏览(136)

我收到错误"Request〈{},any,any,ParsedQs,Record〈string,any〉〉“类型中不存在属性”admin“。此外,nodejs应用程序将不会运行,因为它失败并出现相同的错误。我使用的是typescript x1c 0d1x

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');
    }
}
nuypyhwy

nuypyhwy1#

还要确保正确构建URL,例如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');
    }
}

相关问题