node.js - 为什么验证函数中的令牌参数在 jwt 身份验证中显示错误?
问题描述
我正在尝试进行 jwt 身份验证,并且在验证功能上遇到这样的错误。
没有重载匹配此调用。重载 1 of 3, '(token: string, secretOrPublicKey: Secret, options?: VerifyOptions | undefined): string | 对象',给出了以下错误。'string | 类型的参数 字符串[] | undefined' 不能分配给'string' 类型的参数。类型“未定义”不可分配给类型“字符串”。Overload 2 of 3, '(token: string, 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
. 虽然它不会通过带有虚假令牌的令牌检查,但无论如何它都会运行验证功能。此条件不会缩小类型。
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;
推荐阅读
- android-studio - 我在 android studio 中的 build.gradle 文件出错
- mongodb - Kubernetes(Istio) Mongodb 企业集群:HostUnreachable: Connection reset by peer
- mysql - MySQL搜索和替换特定字符组合
- javascript - 在推送新值之前查找重复项
- regex - 如何在这个正则表达式中允许连字符?
- ubuntu - 如何将域路由到 Apache 中 vs 代码服务器的 8080 端口
- json - 修剪字符串末尾的最后一个字符
- csv - 使用 appscript 从存储桶导入 CSV
- prestashop - 前端模块中的友好 URL 问题 - Prestashop
- python-3.x - 如果包含在二元组或三元组python中,则删除列表中的一元组