Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

node.js - req.headers undefined in middleware of nodeJS typescript

Im new on nodeJS. Im developing a rest API using node and typescript. This api has to read an auth token from the request headers.

in order to do that, i have created a middleware to run on a GET endpoint.

    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();

}

The problem is i cant read req.headers['auth-token'] because "Cannot read property 'auth-token' of undefined", so type a console.log(req.headers) to make sure its undefined, and it is.

Here is the console output:

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

Also, when i call the middleware in the endpoint, it throws an error that i cant understand

here is the route:

   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 code underlines "verifyToken" in the endpoint and this is what it says:

    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>'.

I have tried with:

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

but it doesnt work either. Im 100% sure of sending this auth-token header with POSTMAN enter image description here

This is my app configuration:

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;
question from:https://stackoverflow.com/questions/65892771/req-headers-undefined-in-middleware-of-nodejs-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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();

}

if you see it carefully, you will find that you have swapped the callback type of request and response, express first passes request callback then response callback, so first callback should be of Request Type, then Response, then NextFunction so below is your correct updated middleware code

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();

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...