我一直在为 NestJS 查询参数苦苦挣扎。浏览器正在向此路径发送请求:
/v0/api/patients/674/insurancecard?isFront=true&size=small
但是在服务器上,req
对象上的查询数据如下所示:
{ isFront: [ 'true', 'true' ], size: [ 'small', 'small' ] }
这是在转换之前^^
预计 req.query
看起来像这样:
{ isFront: 'true', size: 'small' }
控制器:
export interface CustomRequest extends Request {
credentials: AuthCredentials;
}
export class InsuranceCardDto {
@IsString()
size: 'small' | 'original';
@IsBoolean()
isFront: boolean;
}
@Controller('patients')
export class PatientsController {
constructor(private readonly pateintsService: PatientsService) {}
@Get(':id/insurancecard')
@UserTypes('employee', 'admin', 'patient')
@UseGuards(IsAuthenticatedGuard, UsersGuard)
@UsePipes(new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true } }))
async insuranceCard(
@Param('id', ParseIntPipe) id: number,
@Query() payload: InsuranceCardDto,
@Req() { credentials: { userType, user } }: CustomRequest,
@Res() res: Response,
) {...}
}
当前服务器配置:
import { HttpException, INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { urlencoded, json } from 'express';
import tlsconfig from './config/tlsconfig';
import { allowedOrigins } from './config';
import { AllExceptionFilter } from './middleware/exceptions.filter';
// import newLogger from './helpers/logger';
export async function bootstrap(): Promise<INestApplication> {
const app = await NestFactory.create(AppModule, { httpsOptions: tlsconfig, logger: ['error'] }); // IF you want to see all logs provide logger to nest. BetterPT Logger works too. Helps for debugging
app.setGlobalPrefix('api');
app.use(json({ limit: '20mb' }));
app.use(urlencoded({ limit: '20mb', extended: true }));
app.useGlobalFilters(new AllExceptionFilter());
// app.useGlobalPipes(new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true } }));
app.enableCors({
origin: (origin, callback) => {
if (origin && !allowedOrigins.includes(origin)) return callback(new HttpException('CORS error', 501), origin);
return callback(null, origin);
},
});
await app.listen(process.env.PORT || 5511);
return app;
}