如何在Node.js中将Post请求获取的JavaScript变量传入XML请求体?
在Node.js中实现将JavaScript变量传入XML请求体调用WebService
针对你要把从POST请求拿到的sorguNo变量塞进XML请求体的需求,这里有两种实用的实现方式,你可以根据自己的场景选择:
方法一:使用ES6模板字符串(简单直接)
如果你的XML结构不算特别复杂,用ES6的模板字符串是最省心的方式,直接把变量嵌入到对应的位置就行,不需要额外依赖。
修改你的代码如下:
router.post('/', async (req, res) => { const sorguNo = req.body.sorguNo; // 从Post请求获取的变量 const url = '你的WebService地址'; const headers = { 'Content-Type': 'text/xml; charset=utf-8', 'soapAction': '你的Soap Action地址' }; // 用模板字符串替换原来的字符串拼接,直接插入变量 const xml = `<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <AuthHeader xmlns="http://你的命名空间地址"> <userName>username</userName> <password>password</password> </AuthHeader> </soap:Header> <soap:Body> <你的请求节点名 xmlns="http://你的命名空间地址"> <sonucNo>${sorguNo}</sonucNo> <!-- 这里直接插入变量 --> </你的请求节点名> </soap:Body> </soap:Envelope>`; // 示例用axios发起请求,你也可以用node-fetch等工具 try { const response = await axios.post(url, xml, { headers }); res.send(response.data); } catch (error) { res.status(500).send(error.message); } });
注意:模板字符串用反引号()包裹,变量用${变量名}`的形式插入,XML里的命名空间和节点名记得替换成你实际的内容。
方法二:使用XML构建库(适合复杂XML结构)
如果你的XML结构比较复杂,或者后续可能有修改,直接拼接字符串容易出错(比如转义问题、标签不闭合),可以用专门的XML构建库,比如xmlbuilder2,它能帮你更规范地生成XML。
步骤如下:
- 先安装依赖:
npm install xmlbuilder2
- 修改代码用库构建XML:
const { create } = require('xmlbuilder2'); const axios = require('axios'); router.post('/', async (req, res) => { const sorguNo = req.body.sorguNo; const url = '你的WebService地址'; const headers = { 'Content-Type': 'text/xml; charset=utf-8', 'soapAction': '你的Soap Action地址' }; // 用xmlbuilder2构建XML const xmlDoc = create({ version: '1.0', encoding: 'utf-8' }) .ele('soap:Envelope', { 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema', 'xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/' }) .ele('soap:Header') .ele('AuthHeader', { xmlns: 'http://你的命名空间地址' }) .ele('userName').txt('username').up() .ele('password').txt('password').up() .up() .up() .ele('soap:Body') .ele('你的请求节点名', { xmlns: 'http://你的命名空间地址' }) .ele('sonucNo').txt(sorguNo).up() // 插入变量 .up() .up() .end({ prettyPrint: true }); // prettyPrint可以让XML格式更美观,可选 // 发起请求 try { const response = await axios.post(url, xmlDoc, { headers }); res.send(response.data); } catch (error) { res.status(500).send(error.message); } });
这种方式的好处是不需要手动拼接XML字符串,库会帮你处理标签闭合、命名空间等问题,后续修改XML结构也更方便。
内容的提问来源于stack exchange,提问作者Ilker Kadir Ozturk
相关产品推荐
相关产品推荐

