【发布时间】:2019-11-09 22:07:12
【问题描述】:
我正在尝试使用 Passport.js、Express 和 TypeScript 在我的应用上设置 Facebook 身份验证策略。感谢this article from Hacker Noon,我可以理解流程的数据流。
但是说到验证回调函数,事情就有点麻烦了。我需要检查用户是否已经登录,因此需要访问 Request 对象。我在passport-facebook 模块文档中检查了passReqToCallback: true 可以在策略选项上设置以启用此功能。
但是,当我将req 参数传递给回调函数时,编译器会抛出以下错误:
Argument of type '(req: Request, accessToken: string, _refreshToken: string, profile: Profile, done: any) => void' is not assignable to parameter of type 'VerifyFunction'.
查看 Passport.js 模块的类型定义,我发现:
export type VerifyFunction =
(accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void;
export type VerifyFunctionWithRequest =
(req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void;
export class Strategy implements passport.Strategy {
constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest);
constructor(options: StrategyOption, verify: VerifyFunction);
name: string;
authenticate(req: express.Request, options?: object): void;
}
所以,理论上,声明
new Strategy(fbConfig, (req: Request, accessToken: string, _refreshToken: string, profile: Profile, done: any) => { ... });
应该毫无问题地被接受。
这是完整的fbConfig 声明:
const fbConfig = {
clientID: "",
clientSecret: "",
callbackURL: "",
passReqToCallback: true,
profileFields: [
"id",
"name",
"birhday",
"gender",
"email",
"location",
"hometown"
]
};
还有我的tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"baseUrl": ".",
"outDir": "dist",
"paths": {
"@models/*": ["./src/models/*"],
"@configs/*": ["./src/configs/*"],
"@controllers/*": ["./src/controllers/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
如果有人能帮我解决这个问题,我将不胜感激!
【问题讨论】:
-
只是为了删除明显的,确保您从“express”导入 { Request },而不是使用 Typescript 的标准库类型定义 Request
-
哦,是的。我肯定会这样做。我以前为这个错误受过很多苦。
标签: node.js typescript express passport.js passport-facebook