如何在NestJS中通过nestjs-soap消费第三方SOAP服务
NestJS使用nestjs-soap调用SOAP服务的实现方案
你现有配置已经完成了SOAP客户端的注册,只需完善service层的调用逻辑即可完成功能,具体实现如下:
完善asyncGetCountryCapital方法
nestjs-soap基于node-soap封装,会自动解析WSDL文件生成对应服务方法,你需要调用的CapitalCity操作可以直接通过注入的客户端实例调用,方法命名规则为「操作名+Async」,返回Promise对象。
完整的方法实现代码:
async asyncGetCountryCapital(countryCode: string = 'IN') { try { // 如需调试请求/响应的原始XML,可打开以下两个事件监听 // this.myDummyClient.on('request', (xml) => console.log('请求XML:', xml)) // this.myDummyClient.on('response', (xml) => console.log('响应XML:', xml)) // 调用SOAP服务,传参对应请求体中的sCountryISOCode字段 const [result] = await this.myDummyClient.CapitalCityAsync({ sCountryISOCode: countryCode }) // 响应已自动转为JSON格式,直接取对应字段即可 return { countryCode: countryCode, capital: result.CapitalCityResult } } catch (error) { // 可根据业务需要替换为自定义业务异常 throw new Error(`SOAP服务调用失败:${error.message}`) } }
逻辑说明
- 不需要手动拼接XML请求体、手动设置请求头,客户端会根据WSDL定义自动生成符合规范的请求内容
- 调用返回的结果是数组结构,第一个元素为解析后的JSON响应数据,对应原XML响应中的
<m:CapitalCityResponse>节点内容 - 方法默认查询印度(IN)的首都,也可以传入其他国家ISO码查询对应国家首都
快速测试(可选)
如果需要验证功能是否正常,可以在app.controller.ts中新增测试路由:
import { Controller, Get, Query } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} // 原有路由省略... @Get('country-capital') getCountryCapital(@Query('code') code: string) { return this.appService.asyncGetCountryCapital(code); } }
启动项目后访问http://localhost:3000/country-capital?code=CN即可测试查询中国首都的结果。
内容的提问来源于stack exchange,提问作者Sushant Saurav
相关产品推荐
相关产品推荐

