typescript 在TSOA中使用cookie解析器(快速中间件)

7gyucuyw  于 2022-12-05  发布在  TypeScript
关注(0)|答案(1)|浏览(167)

在express应用程序中,您可以像这样使用cookie解析器:

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function (req, res) {
  // Cookies that have not been signed
  console.log('Cookies: ', req.cookies)

  // Cookies that have been signed
  console.log('Signed Cookies: ', req.signedCookies)
})

app.listen(8080)

我在我的应用程序中使用TSOA,所以我不确定如何在代码中使用中间件,例如app.use(cookieParser())
我尝试过:

import { Controller, Route, Get, Tags, Request, Middlewares } from 'tsoa';
import { fetchTopFiveTracks } from './routes/fetchTopFiveTracks';
import express from 'express';
import cookieParser from 'cookie-parser';

interface MultipleArtistsResponse {
  artistsSpotify: unknown[];
}
@Middlewares({ express: [cookieParser] })
@Route('/TopFiveTracksController') // route name => localhost:xxx/TopFiveTracksController
@Tags('TopFiveTracksController') // => Under TopFiveTracksController tag
export class TopFiveTracksController extends Controller {
  @Get() //specify the request type
  public async topFiveTracks(
    @Request() request: express.Request,
  ): Promise<MultipleArtistsResponse> {
    try {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
      const accessT = request.cookies.accessToken;
      const artistsSpotify = await fetchTopFiveTracks<MultipleArtistsResponse>({
        method: 'GET',
        credentials: 'same-origin',
        headers: {
          Accept: 'application/json',
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-call
          Authorization: `Bearer ${accessT}`,
          'Content-Type': 'application/json',
        },
      });
      console.log(accessT);
      console.log({ artistsSpotify });
      return artistsSpotify;
    } catch (error) {
      throw new Error(JSON.stringify(error));
    }
  }
}

正如您所看到的,我已经尝试过为TSOA使用@ Middlewaresdecorator,但是我得到了错误:Route.get()需要一个回调函数,但得到了一个[object Object]。
在添加@ Middlewaresdecorator和cookieParser中间件之前,我的应用程序工作正常。据我所知,这个错误主要与忘记导出一个所需的方法有关。
你知道如何在TSOA中正确使用cookieParser中间件吗?谢谢!

lf5gs5x2

lf5gs5x21#

哇!我运行了和你一样的错误。试着让它像这样:@Middlewares(cookieParser)

  • 另请记住,已在tsconfig.json .1中将experimentalDecorators设置为true *

因此,您的代码应该如下所示:

import { Controller, Route, Get, Tags, Request, Middlewares } from 'tsoa';
import { fetchTopFiveTracks } from './routes/fetchTopFiveTracks';
import express from 'express';
import cookieParser from 'cookie-parser';

interface MultipleArtistsResponse {
  artistsSpotify: unknown[];
}
@Middlewares(cookieParser)
@Route('/TopFiveTracksController') // route name => localhost:xxx/TopFiveTracksController
@Tags('TopFiveTracksController') // => Under TopFiveTracksController tag
export class TopFiveTracksController extends Controller {
  @Get() //specify the request type
  public async topFiveTracks(
    @Request() request: express.Request,
  ): Promise<MultipleArtistsResponse> {
    try {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
      const accessT = request.cookies.accessToken;
      const artistsSpotify = await fetchTopFiveTracks<MultipleArtistsResponse>({
        method: 'GET',
        credentials: 'same-origin',
        headers: {
          Accept: 'application/json',
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-unsafe-call
          Authorization: `Bearer ${accessT}`,
          'Content-Type': 'application/json',
        },
      });
      console.log(accessT);
      console.log({ artistsSpotify });
      return artistsSpotify;
    } catch (error) {
      throw new Error(JSON.stringify(error));
    }
  }
}

没有提到一个带有键“express”({ express: [function] })的对象。我认为这可以作为一个例子。
PS系列
有一种选择是拥有多个中间件,只需将它们放入数组即可:@Middlewares([funcA, funcB])
PPS系统
您还可以定义中间件,如下所示:

import { Request, Response, NextFunction } from 'express';

// ... controller logic ...

// @Get('/endpoint') | @Post('/endpoint') etc.
@Middlewares([
  (req: Request, res: Response, next: NextFunction) => {
    console.log(req.headers);
    next();
  },
  (req: Request, res: Response, next: NextFunction) => {
    console.log('Second middleware, but we can also use only one!');
    next();
  },
])
// getEndpoint(): string {
//   return 'Hello World!';
// }

// ... controller logic ...

1https://www.example.comgithub.com/lukeautry/tsoa/pull/1123#issuecomment-1018251162

相关问题