req.headers 在 nodeJS 打字稿的中间件中未定义

req.headers undefined in middleware of nodeJS typescript

我是 nodeJS 的新手。我正在使用节点和打字稿开发休息 API。此 api 必须从请求 header 中读取身份验证令牌。

为了做到这一点,我在 GET 端点上为 运行 创建了一个中间件。

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


export const verifyToken = (res: Response, req: Request, next: NextFunction) => {

    //reading the headers
    const token = req.headers['auth-token'];
    if (!token){
        return res.status(403).json({message: 'auth-token missing'})
    }
    next();

}

问题是我无法读取 req.headers['auth-token'] 因为“无法读取未定义的 属性 'auth-token'”,所以输入 console.log( req.headers) 以确保其未定义,并且确实如此。

控制台输出如下:

(node:8372) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'auth-token' of undefined

此外,当我调用端点中的中间件时,它会抛出一个我无法理解的错误

这是路线:

   import Router from 'express'
    
    import * as TiendaCtrl from '../controllers/tienda.controller'
    import {verifyToken} from '../middlewares/verifyToken'
    
    const router = Router();
    
    //here is the endpoint
    router.get('/tiendas',  verifyToken  , TiendaCtrl.getTiendas);
export default router;

VS 代码在端点中为“verifyToken”加下划线,这就是它所说的:

    error TS2769: No overload matches this call.
[0]   Overload 1 of 4, '(path: PathParams, ...handlers: RequestHandler<ParamsDictionary, any, any, ParsedQs>[]): Express', gave the following error.
[0]     Argument of type '(res: Response, req: Request, next: NextFunction) => Response<any> | undefined' is not assignable to parameter of type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
[0]       Types of parameters 'res' and 'req' are incompatible.
[0]         Type 'Request<ParamsDictionary, any, any, ParsedQs>' is missing the following properties from type 'Response<any>': status, sendStatus, links, send, and 53 more.
[0]   Overload 2 of 4, '(path: PathParams, ...handlers: RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>[]): Express', gave the following error.
[0]     Argument of type '(res: Response, req: Request, next: NextFunction) => Response<any> | undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
[0]       Type '(res: Response, req: Request, next: NextFunction) => Response<any> | undefined' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.

我试过:

const token = req.header('auth-token');

但它也不起作用。 我 100% 肯定会用 POSTMAN 发送这个 auth-token header enter image description here

这是我的应用配置:

import express from 'express'
import tiendasRoutes from './routes/tiendas.routes'
import authRoutes from './routes/auth.routes'

const app = express();



const bodyParser = require ('body-parser');
const cors = require('cors');
const morgan = require('morgan');


//Settings
app.set('port', process.env.PORT || 3000);

//Middlewares
app.use(morgan('dev'));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());


//Routes

app.use('/api',tiendasRoutes);
app.use('/api',authRoutes)



export default app;
export const verifyToken = (res: Response, req: Request, next: NextFunction) => {

    //reading the headers
    const token = req.headers['auth-token'];
    if (!token){
        return res.status(403).json({message: 'auth-token missing'})
    }
    next();

}

仔细看会发现你调换了request和response的回调类型,express先是request callback,然后是response callback,所以callback应该是Request Type,然后是Response,然后是NextFunction 所以下面是你正确更新的中间件代码

export const verifyToken = (req: Request, res: Response, next: NextFunction) => {

    //reading the headers
    const token = req.headers['auth-token'];
    if (!token){
        return res.status(403).json({message: 'auth-token missing'})
    }
    next();

}