为什么verify函数中的token参数在jwt身份验证中显示错误



我正在尝试进行jwt身份验证,但在验证函数中遇到了这样的错误。

没有与此调用匹配的重载。重载第1个,共3个,"(token:string,secretOrPublicKey:Secret,options?:VerifyOptions|undefined(:string|object",给出以下错误。类型为"string|string[]| undefined"的参数不可分配给类型为"string"的参数。类型"undefined"不可分配给类型"string"。重载第2个(共3个(,"(标记:字符串,secretOrPublicKey:Secret | GetPublicKeyOrSecret,callback?:VerifyCallback | undefined(:void",给出以下错误。

import { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import config from "../config/default"
var authorization = function (req:Request, res:Response, next:NextFunction) {
var token = req.headers['x-access-token'];
var msg = {auth: false, message: 'No token provided.'};
if (!token) res.status(500).send(msg);
jwt.verify(token, config.token.secret, function (err) {
var msg = {auth: false, message: 'Failed to authenticate token.'};
if (err) res.status(500).send(msg);
next();
});
}
module.exports = authorization;

问题是req.headers返回类型为string | string[] | undefined的值。您正试图将它作为一个参数传递给在该位置需要类型string的函数。因此出现了错误。

你的代码有一些问题,你必须解决才能解决:

  • if (!token) res.status(500).send(msg)函数执行之后没有停止。它将进入jwt.verify。尽管它不会通过带有falsy令牌的令牌检查,但它无论如何都会运行验证函数。此条件不会缩小类型
declare const n: number | null
if (!n) {
console.log('0, NaN or null')
} else {
type N = typeof n // N ~ number
}
if (!n) console.log('0, NaN or null')
type M = typeof n // M ~ number | null

游乐场连接

  • token可以是字符串数组

要使代码进行类型检查并正常工作,必须将token的类型缩小到string:

import { NextFunction, Request, Response } from "express";
import jwt, { VerifyErrors } from "jsonwebtoken";
import config from "../config/default"
var authorization = function (req:Request, res:Response, next:NextFunction) {
var token = req.headers['x-access-token'];
var msg = {auth: false, message: 'No token provided.'};
// check whether `token` is an array and get the first element
// narrows the type to `string | undefined`
if (Array.isArray(token)) token = token[0];
// narrows the type to `string`
if (!token) {
res.status(500).send(msg);
// return early and prevent execution of the underlying middlewares
return next(false); 
}
jwt.verify(token, config.token.secret, function (err: VerifyErrors | null) {
var msg = {auth: false, message: 'Failed to authenticate token.'};
if (err) res.status(500).send(msg);
next();
});
}
module.exports = authorization;

最新更新