在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中间件吗?谢谢!
1条答案
按热度按时间lf5gs5x21#
哇!我运行了和你一样的错误。试着让它像这样:
@Middlewares(cookieParser)
tsconfig.json
.1中将experimentalDecorators
设置为true
*因此,您的代码应该如下所示:
没有提到一个带有键“express”(
{ express: [function] }
)的对象。我认为这可以作为一个例子。PS系列
有一种选择是拥有多个中间件,只需将它们放入数组即可:
@Middlewares([funcA, funcB])
PPS系统
您还可以定义中间件,如下所示:
1https://www.example.comgithub.com/lukeautry/tsoa/pull/1123#issuecomment-1018251162