【问题标题】:req.headers undefined in middleware of nodeJS typescriptnodeJS typescript的中间件中未定义req.headers
【发布时间】:2021-01-25 21:34:21
【问题描述】:

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

为了做到这一点,我创建了一个在 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 标头 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;

【问题讨论】:

  • 添加了答案,让我知道它是否有效
  • 您的问题标题为res.headers。你的意思是req.headers
  • @jfriend00。它的req.headers。搞错了

标签: node.js typescript token middleware


【解决方案1】:
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的callback类型调换了,express先传request回调再传response回调,所以第一个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();

}

【讨论】:

  • 成功了!我现在必须休息,因为这令人担忧哈哈哈哈。谢谢
  • @JorgeCróquer,很高兴为您提供帮助
  • @JorgeCróquer,如果这是您想要的,您可以将此答案标记为已接受
  • 我标记了它,但我没有 15 个声望点,所以它不会显示标记。但是谢谢,这有效
猜你喜欢
  • 2020-08-19
  • 2017-07-24
  • 2023-03-20
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
相关资源
最近更新 更多