在 Nest.js 中的 Post 的请求正文中获取 XML

Obtaining XML in the Request Body for Post in Nest.js

我很好奇是否可以在Nest.js的Request Body中获取XML数据。

依赖关系

"dependencies": {
    "@nestjs/common": "^7.0.0",
    "@nestjs/core": "^7.0.0",
    "@nestjs/platform-express": "^7.0.0",

要求

我希望有一个名为 /EPCIS/capture 的 HTTP POST API 可以获取如下 XML 文档:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<epcis:EPCISDocument
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:epcis="urn:epcglobal:epcis:xsd:1"
    xmlns:epcglobal="urn:epcglobal:xsd:1"
    xsi:schemaLocation="urn:epcglobal:epcis:xsd:1 EPCglobal-epcis-1_0.xsd"
    creationDate="2008-03-16T22:13:16.397+01:00"
    schemaVersion="1.0">
  <EPCISBody>
    <EventList>
      <ObjectEvent>
        <eventTime>2008-03-16T22:13:16.397+01:00</eventTime>
        <eventTimeZoneOffset>+01:00</eventTimeZoneOffset>
        <epcList>
          <epc>urn:epc:id:sgtin:0614141.107346.2017</epc>
          <epc>urn:epc:id:sgtin:0614141.107346.2018</epc>
        </epcList>
        <action>OBSERVE</action>
        <bizStep>urn:epcglobal:epcis:bizstep:fmcg:shipped</bizStep>
        <disposition>urn:epcglobal:epcis:disp:fmcg:unknown</disposition>
        <readPoint>
          <id>urn:epc:id:sgln:0614141.07346.1234</id>
        </readPoint>
        <bizLocation>
          <id>urn:epcglobal:fmcg:loc:0614141073467.A23-49</id>
        </bizLocation>
        <bizTransactionList>
          <bizTransaction type="urn:epcglobal:fmcg:btt:po">
            http://transaction.acme.com/po/12345678
          </bizTransaction>
        </bizTransactionList>
      </ObjectEvent>
    </EventList>
  </EPCISBody>
</epcis:EPCISDocument>

在我的控制器中:


Post('capture')
    addEPCDocument(@Body() epcDocument: any): any {
        console.log(epcDocument)
    }

但我得到的只是 {} 在记录传入的请求正文时。我的 POSTMAN 设置已经提到:

Content-Type: application/xml

并且在 Body 中我粘贴了上面提到的 XML。响应是 HTTP 400 错误请求。

从 Nest.JS 中的请求正文中提取 XML 的通常方法是什么?

Nest 附带 body-parser pre-defined, but you can modify the configurations it uses to work with xml. By default, it will only work with application/json and applicaiton/x-www-form-urlencoded. You can use a different middleware for parsing the xml requests, like this one

正如 Jay 提到的,可以添加用于解析 xml 请求的中间件。

xml.middleware.ts

import { Injectable, NestMiddleware } from '@nestjs/common';
import * as bodyParser from 'body-parser';

const bodyParserXML = bodyParser.text({
  type: 'application/xml',
});

@Injectable()
export class XMLMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    parserXML(req, res, next);
  }
}

在app.module.ts

中添加这个中间件
import { XMLMiddleware } from './middileware/xml.middleware';

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(XMLMiddleware).forRoutes({
      path: '/*',
      method: RequestMethod.GET,
    });
  }
}

参考:https://chowdera.com/2022/117/202204271800482265.html