You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

passport-jwt报错:JwtStrategy需获取JWT的函数,求技术支持

排查Passport-JWT的TypeError问题:JwtStrategy requires a function to retrieve jwt from requests

问题根源

嘿,我一眼就发现问题所在了——你在配置JwtStrategy时犯了一个极易忽略的拼写错误!这个报错的核心原因是,你把Passport-JWT要求的配置属性名写错了,导致库无法识别你提供的JWT提取函数。

错误代码定位

看你提供的passport.js代码片段:

const opts = {};
opts.jwtFromrequest = ExtractJwt.fromAuthHeaderWithScheme('jwt') // 这里的属性名拼写错误!
opts.secretOrKey = keys.secretkey

Passport-JWT的官方配置要求这个选项的名称是**jwtFromRequest**(遵循驼峰命名规范,Request的首字母R为大写),而你写成了小写的jwtFromrequest,库会默认你没有提供这个必填配置项,因此抛出了报错。

修正后的代码

只需要把属性名改成正确的jwtFromRequest即可,修正后的passport.js代码如下:

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model('users');
const keys = require('../config/keys');

const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt') // 修正属性名拼写
opts.secretOrKey = keys.secretkey

module.exports = passport => {
  passport.use(new JwtStrategy(opts,function(jwt_payload,done){
    User.findById(jwt_payload.id)
      .then(user=>{
        if(user){
          return done(null,user)
        }
        return done(null,false)
      })
      .catch(err=>console.log(err))
  }))
}

额外检查建议

  1. 确认keys.secretkey是正确的密钥值,没有拼写错误
  2. 确保ExtractJwt.fromAuthHeaderWithScheme('jwt')的使用和前端的传参方式匹配(比如如果前端用的是Bearer认证方案,需要改成fromAuthHeaderWithScheme('Bearer'),不过这里你用jwt只要前端对应就没问题)

内容的提问来源于stack exchange,提问作者Hadi Husain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:17:47