typescript - NestJS:查询参数作为字符串数组传入
问题描述
我一直在为 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;
}
解决方案
推荐阅读
- android - 使用 SimpleXmlConverterFactory / Kotlin 解析 XML 数组
- java - 在 DropWizard 或 Jetty 应用程序中导致 404 的日志 URL
- oracle - 为什么这个函数会带来空值?
- oracle-data-integrator - 在 ODI 12C 中使用 SQL 覆盖,源数据服务器与目标不同
- c++ - 尝试执行任何需要它的操作时,无法修复 WinAPI 中的“无效句柄”错误
- flutter - 表单的 TextFormField 中的多个光标颤动
- r - “data.table”中的“everything()”运算符等价于什么?
- c# - 使用 Eval 的空值条件语句
- node.js - 使用旧节点 v 0.10.40 将 Meteor bcrypt 部署到服务器的问题
- optimization - WORHP 中的优化参数缩放