结合TypeScript Koa-Router和Passport。

问题描述 投票:2回答:1

我是Typescript中的新手,并试图将其整合到一起 koa-routerkoa-passport. 安装了所有 @types\

import Koa from "koa";
import Route from "koa-router";
import passport from "koa-passport";
import session from "koa-session";

const app = new Koa();
const router = new Route();
app.keys = [process.env.SECRET_KEY || "secret"];
app.use(session({}, app));
app.use(passport.initialize());
app.use(passport.session());

app.use(router.routes()).use(router.allowedMethods());

而当我尝试使用 passport 方法与 router.

router.post("Logout", "/logout", ctx => {
  if (ctx.isAuthenticated()) {
    ctx.logout();
  }
});

在context(ctx)方法上有错误

Property 'isAuthenticated' does not exist on type 'ParameterizedContext<any, IRouterParamContext<any, {}>>'.
Property 'logout' does not exist on type 'ParameterizedContext<any, IRouterParamContext<any, {}>>'.

我尝试了不同的方法,但不成功。感谢任何帮助。

node.js typescript passport.js koa2 koa-router
1个回答
0
投票

我发现有一种方法是将所有的路由和护照的功能和类型定义为单独的 typeof KoaPassport. 路线 as Koa.Middleware 也有这个问题

// src/index.ts
import routes from "./routes";
...
routes(router, model, passport);
// src/routes/index.ts
function routes(router: Route, model: Model, passport: typeof KoaPassport) {
  router
        .post("Login", "/login", (async (ctx, next) => {
            await passport.authenticate("local", async (err, user) => {
                  ....
            })(ctx, next);
        }) as Koa.Middleware)
}
© www.soinside.com 2019 - 2024. All rights reserved.