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

Node.js集成Passport服务时遇TypeError: passport.use is not a function错误求助

Passport集成报错:TypeError: passport.use is not a function

错误信息

file:///home/sirbt/Desktop/UberAds/passport-config.js:37
    passport.use(new LocalStrategy({ usernameField: 'loginEmailAddress'}, authenticateUser ))
             ^

TypeError: passport.use is not a function
    at initialize (file:///home/sirbt/Desktop/UberAds/passport-config.js:37:14)
    at file:///home/sirbt/Desktop/UberAds/server.js:32:28
    at ModuleJob.run (internal/modules/esm/module_job.js:170:25)
    at async Loader.import (internal/modules/esm/loader.js:178:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)

相关代码文件

./passport-config.js

import { Strategy as LocalStrategy } from "passport-local";
import * as passport from "passport";
import pkg1 from 'bcrypt';
const {bcrypt } = pkg1;

export default function initialize( _passport, getUserByEmail, getUserById ) {
    const authenticateUser = async  (loginEmailAddress, loginPasswordSignIn, done) => {
        const user = getUserByEmail(loginEmailAddress)

        if(user == null) {
            return done(null, false, {message: 'No user with that email' });
        }

        try {
            if( await bcrypt.compare(loginPasswordSignIn, user.password)){
                return done(null, user, { message:'Password incorrect' })
            } else {
                return done(null, false, { message:'Password incorrect' })
            }

        } catch (e) {
            return done(e)            
        }
    }

    passport.use(new LocalStrategy({ usernameField: 'loginEmailAddress'}, authenticateUser ))
    passport.serializeUser((user, done) => done( null, user.id ) )
    passport.deserializeUser((id, done) => {
        return done( null, getUserById(id) ) 
    })

}

./server.js

import express from 'express';
import mongodb from 'mongodb';
import Collection from 'mongodb';
import bcrypt from 'bcrypt';
import pkg3 from 'passport';
const { passport } = pkg3;

import pkg from 'express-flash';
const { flash } = pkg;

import pkg2 from 'express-session';
const { session } = pkg2;

import initialize from './passport-config.js';
const initializePassport = initialize();

initializePassport ( 
    passport, 
    email => users.find(user => user.email === email),
    id => users.find(user => user.id === id)
);

const bcryptt = bcrypt;
const MongoClient = mongodb.MongoClient;
const app  = express();

app.use(express.static ('public'));
app.use(express.json() );
app.use(express.urlencoded({ extended: true }));
app.use( flash() );
app.use( session({
    secret: process.env.SESSION_SECRET, 
    resave: false,
    saveUninitialized: false
}) );

app.use(passort.initialize());
app.use(passort.session());
app.use('/css', express.static(__dirname + 'public/css'));
app.use('/js', express.static(__dirname + 'public/js'));
app.use('/images', express.static(__dirname + 'public/images'));
app.use('/fonts', express.static(__dirname + 'public/fonts'));
app.set('view engine', 'ejs');

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.route('/advertiserLogin')
    .get((req, res)=>{ 
        res.render('advertiserLogin', {name: "Sir BT!"});
    })

    .post( passport.authenticate('local', {
        successRedirect: '/advertiser',
        failureRedirect: '/advertiserLogin',
        failureFlash: true

    }) );


app.listen (7000)

./package.json

{
  "name": "smartqueues",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "type": "module",
  "scripts": {
    "start": "babel src --out-dir dist",
    "devStart": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/mongodb": "^4.0.7",
    "babel-cli": "^6.26.0",
    "bcrypt": "^5.0.1",
    "ejs": "^3.1.8",
    "express": "^4.18.1",
    "express-ejs-layouts": "^2.5.1",
    "express-flash": "^0.0.2",
    "express-session": "^1.17.3",
    "mongodb": "^4.7.0",
    "mongoose": "^6.4.0",
    "passport": "^0.6.0",
    "passport-local": "^1.0.0",
  },
  "devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/core": "^7.18.5",
    "@babel/preset-env": "^7.18.2",
    "nodemon": "^2.0.16"
  }
}

问题分析与修复方案

1. passport-config.js 核心错误:误用导入的passport实例

函数initialize接收的参数是_passport,但内部调用passport.use时用的是顶部导入的passport,而非传入的实例。修改如下:

// 替换原passport.use等三行代码
_passport.use(new LocalStrategy({ usernameField: 'loginEmailAddress'}, authenticateUser ))
_passport.serializeUser((user, done) => done( null, user.id ) )
_passport.deserializeUser((id, done) => {
    return done( null, getUserById(id) ) 
})

2. passport-config.js bcrypt导入错误

bcrypt是默认导出,无需解构:

// 替换原bcrypt导入代码
import bcrypt from 'bcrypt';

3. passport-config.js 密码验证逻辑反转

bcrypt.compare返回true时代表密码匹配,应返回用户;false时才是密码错误:

// 替换原try块内容
try {
    if( await bcrypt.compare(loginPasswordSignIn, user.password)){
        return done(null, user) // 密码正确,返回用户
    } else {
        return done(null, false, { message:'Password incorrect' })
    }
} catch (e) {
    return done(e)            
}

4. server.js passport导入错误

passport是默认导出,直接导入即可:

// 替换原passport导入代码
import passport from 'passport';

5. server.js initialize函数调用错误

无需提前执行initialize(),直接传入参数调用:

// 替换原initialize相关代码
import initialize from './passport-config.js';

// 先定义users变量(示例用空数组,实际需从数据库获取)
const users = [];

initialize( 
    passport, 
    email => users.find(user => user.email === email),
    id => users.find(user => user.id === id)
);

6. server.js 拼写错误

passort.initialize()和passort.session()中的passort是拼写错误,改为passport:

app.use(passport.initialize());
app.use(passport.session());

7. server.js 缺失path模块导入

使用fileURLToPath和path.dirname前需导入相关模块:

// 在文件顶部添加
import { fileURLToPath } from 'url';
import path from 'path';

8. server.js 静态资源路径错误

__dirname + 'public/css'会导致路径拼接错误,改为path.join(__dirname, 'public/css'):

app.use('/css', express.static(path.join(__dirname, 'public/css')));
app.use('/js', express.static(path.join(__dirname, 'public/js')));
app.use('/images', express.static(path.join(__dirname, 'public/images')));
app.use('/fonts', express.static(path.join(__dirname, 'public/fonts')));

其他注意事项

  • 确保SESSION_SECRET环境变量已正确设置,Linux/macOS可通过export SESSION_SECRET=your_secret_key设置,Windows命令行用set SESSION_SECRET=your_secret_key。
  • 示例中users数组为临时存储,实际应用需连接MongoDB查询用户数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:39:16