参考网上方案,比较优雅的实现方式,解决各类支付回调及企业微信回调XML格式解析问题
引入fast-xml-parser
npm install fast-xml-parser
修改 src\main.ts
import bodyParser from 'body-parser';
// 在NestFactory.create后插入
app.use(bodyParser.text({ type: 'application/xml' }));
app.use(bodyParser.text({ type: 'text/xml' }));
创建xml.decorator类
根据自己的目录情况新建xml.decorator.ts文件,代码为
import {
BadRequestException,
createParamDecorator,
ExecutionContext,
} from '@nestjs/common';
import { XMLParser, XMLValidator } from 'fast-xml-parser';
export const XML = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const { body } = ctx.switchToHttp().getRequest();
// 根据fast-xml-parser版本不同初始化方式不一样这里版本是V4
if (XMLValidator.validate(body) !== true) {
throw new BadRequestException('Invalid XML');
}
const parser = new XMLParser();
return = parser.parse(body);
},
);
在Controller中使用
@Post('command')
command(@XML() data: any) {
console.log('command', data);
return data;
}