typescript - การใช้ cookie-parser (middleware ของ express) ใน TSOA
ในแอป express คุณจะใช้ cookie-parser แบบนี้:
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 ในแอปพลิเคชันของฉัน ดังนั้นฉันก็ไม่แน่ใจจริงๆ ว่าจะใช้ middleware ในโค้ดของฉันแบบนี้ 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));
}
}
}
อย่างที่คุณเห็น ผมได้ลองใช้ตัวตกแต่ง @Middlewares สำหรับ TSOA แล้ว แต่ผมได้รับข้อผิดพลาด: Route.get() ต้องการฟังก์ชัน callback แต่ได้รับ [object Object]
ก่อนที่จะเพิ่มตัวตกแต่ง @Middlewares พร้อมกับมิดเดิลแวร์ cookieParser แอปพลิเคชันของฉันทำงานได้ตามปกติ จากที่ฉันทราบ ข้อผิดพลาดนี้ส่วนใหญ่เกี่ยวข้องกับการลืมส่งออกเมธอดที่จำเป็น
มีใครพอทราบไหมว่าฉันสามารถใช้งาน cookieParser middleware ใน TSOA ได้อย่างถูกต้องอย่างไร? ขอบคุณ!
คำตอบ #1
ว้าว! ฉันเจอข้อผิดพลาดเดียวกับคุณ ลองทำแบบนี้ดู: @Middlewares(cookieParser)
นอกจากนี้อย่าลืมตั้งค่า experimentalDecorators เป็น true ใน tsconfig.json ของคุณ1
ดังนั้นโค้ดของคุณควรจะดูเหมือนแบบนี้:
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] }) ฉันคิดว่านี่สามารถใช้เป็นตัวอย่างได้
ป.ล.
มีตัวเลือกในการใช้มิดเดิลแวร์หลายตัว เพียงแค่ใส่พวกมันลงในอาร์เรย์: @Middlewares([funcA, funcB])
พีพีเอส
คุณก็สามารถกำหนด middleware ของคุณแบบนั้นได้เช่นกัน:
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 ...
1 https://github.com/lukeautry/tsoa/pull/1123#issuecomment-1018251162
