@13w/soap 中文文档教程
Soap
node.js 的 SOAP 客户端和服务器。
该模块允许您使用 SOAP 连接到 Web 服务。 它还提供了一个服务器,允许您运行自己的 SOAP 服务。
- Features:
- Install
- Why can't I file an issue?
- Where can I find help?
- Module
- soap.createClient(url[, options], callback) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
- soap.createClientAsync(url[, options]) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
- soap.listen(server, path, services, wsdl) - create a new SOAP server that listens on path and provides services.
- Options
- Server Logging
- Server Events
- Server Response on one-way calls
- SOAP Fault
- Server security example using PasswordDigest
- Server connection authorization
- SOAP Headers
- Received SOAP Headers
- Outgoing SOAP Headers
- Client
- Client.describe() - description of services, ports and methods as a JavaScript object
- Client.setSecurity(security) - use the specified security protocol
- Client.method(args, callback) - call method on the SOAP service.
- Client.methodAsync(args) - call method on the SOAP service.
- [Client.service.port.method(args, callback[, options[, extraHeaders]]) - call a method using a specific service and port](#clientserviceportmethodargs-callback-options-extraheaders---call-a-method-using-a-specific-service-and-port)
- Overriding the namespace prefix
- Client.lastRequest - the property that contains last full soap request for client logging
- Client.setEndpoint(url) - overwrite the SOAP service endpoint address
- Client Events
- Security
- BasicAuthSecurity
- BearerSecurity
- ClientSSLSecurity
- ClientSSLSecurityPFX
- WSSecurity
- WSSecurityCert
- NTLMSecurity
- Handling XML Attributes, Value and XML (wsdlOptions).
- Overriding the
value
key - Overriding the
xml
key - Overriding the
attributes
key - Specifying the exact namespace definition of the root element
- Custom Deserializer
- Handling "ignored" namespaces
- Handling "ignoreBaseNameSpaces" attribute
- soap-stub
- Example
- Contributors
Features:
- Very simple API
- Handles both RPC and Document schema types
- Supports multiRef SOAP messages (thanks to @kaven276)
- Support for both synchronous and asynchronous method handlers
- WS-Security (currently only UsernameToken and PasswordText encoding is supported)
- Supports express based web server(body parser middleware can be used)
Install
使用 npm 安装:
npm install soap
Why can't I file an issue?
我们已在存储库中禁用问题,现在仅审查拉取请求。 可以在此处找到我们禁用问题的原因 #731。
Where can I find help?
可以在 gitter 上找到社区支持:
如果您正在寻找专业帮助,您可以通过此谷歌表单。
Module
soap.createClient(url[, options], callback) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClient(url, function(err, client) {
client.MyFunction(args, function(err, result) {
console.log(result);
});
});
这个客户端有一个内置的 WSDL 缓存。 您可以使用 disableCache
选项来禁用它。
soap.createClientAsync(url[, options]) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClientAsync(url).then((client) => {
return client.MyFunctionAsync(args);
}).then((result) => {
console.log(result);
});
这个客户端有一个内置的 WSDL 缓存。 您可以使用 disableCache
选项来禁用它。
Options
options
参数允许您使用以下属性自定义客户端:
- endpoint: to override the SOAP service's host specified in the
.wsdl
file. - envelopeKey: to set specific key instead of
<pre><soap:Body></soap:Body></pre>
. - preserveWhitespace: to preserve leading and trailing whitespace characters in text and cdata.
- escapeXML: escape special XML characters in SOAP message (e.g.
&
,>
,<
etc), default:true
. - suppressStack: suppress the full stack trace for error messages.
- returnFault: return an
Invalid XML
SOAP fault on a bad request, default:false
. - forceSoap12Headers: to set proper headers for SOAP v1.2.
- httpClient: to provide your own http client that implements
request(rurl, data, callback, exheaders, exoptions)
. - request: to override the request module.
- wsdl_headers: custom HTTP headers to be sent on WSDL requests.
- wsdl_options: custom options for the request module on WSDL requests.
- disableCache: don't cache WSDL files, request them every time.
- overridePromiseSuffix: if your wsdl operations contains names with Async suffix, you will need to override the default promise suffix to a custom one, default:
Async
. - normalizeNames: if your wsdl operations contains names with non identifier characters (
[^a-z$_0-9]
), replace them with_
. Note: if using this option, clients using wsdls with two operations likesoap:method
andsoap-method
will be overwritten. Then, use bracket notation instead (client['soap:method']()
). - namespaceArrayElements: provides support for nonstandard array semantics. If true, JSON arrays of the form
{list: [{elem: 1}, {elem: 2}]}
are marshalled into xml as<list><elem>1</elem></list> <list><elem>2</elem></list>
. If false, marshalls into<list> <elem>1</elem> <elem>2</elem> </list>
. Default:true
.
注意:对于 node >0.10.X 的版本,您可能需要指定 {connection: 'keep-alive'}
在 SOAP 标头中,以避免截断较长的分块响应。
soap.listen(server, path, services, wsdl) - create a new SOAP server that listens on path and provides services.
server 可以是 http 服务器或 express 基于框架的服务器 wsdl 是定义服务的 xml 字符串。
var myService = {
MyService: {
MyPort: {
MyFunction: function(args) {
return {
name: args.name
};
},
// This is how to define an asynchronous function with a callback.
MyAsyncFunction: function(args, callback) {
// do some work
callback({
name: args.name
});
},
// This is how to define an asynchronous function with a Promise.
MyPromiseFunction: function(args) {
return new Promise((resolve) => {
// do some work
resolve({
name: args.name
});
});
},
// This is how to receive incoming headers
HeadersAwareFunction: function(args, cb, headers) {
return {
name: headers.Token
};
},
// You can also inspect the original `req`
reallyDetailedFunction: function(args, cb, headers, req) {
console.log('SOAP `reallyDetailedFunction` request from ' + req.connection.remoteAddress);
return {
name: headers.Token
};
}
}
}
};
var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
//http server example
var server = http.createServer(function(request,response) {
response.end('404: Not Found: ' + request.url);
});
server.listen(8000);
soap.listen(server, '/wsdl', myService, xml);
//express server example
var app = express();
//body parser middleware are supported (optional)
app.use(bodyParser.raw({type: function(){return true;}, limit: '5mb'}));
app.listen(8001, function(){
//Note: /wsdl route will be handled by soap module
//and all other routes & middleware will continue to work
soap.listen(app, '/wsdl', myService, xml);
});
Options
您可以传入服务器和 WSDL 选项 使用选项哈希。
服务器选项包括以下内容:
pfx
: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the key, cert and ca options.)key
: A string or Buffer containing the private key of the server in PEM format. (Could be an array of keys). (Required)passphrase
: A string of passphrase for the private key or pfx.cert
: A string or Buffer containing the certificate key of the server in PEM format. (Could be an array of certs). (Required)ca
: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.crl
: Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)ciphers
: A string describing the ciphers to use or exclude, separated by :. The default cipher suite is:enableChunkedEncoding
: A boolean for controlling chunked transfer encoding in response. Some client (such as Windows 10's MDM enrollment SOAP client) is sensitive to transfer-encoding mode and can't accept chunked response. This option let user disable chunked transfer encoding for such a client. Default totrue
for backward compatibility.
var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
soap.listen(server, {
// Server options.
path: '/wsdl',
services: myService,
xml: xml,
// WSDL options.
attributesKey: 'theAttrs',
valueKey: 'theVal',
xmlKey: 'theXml'
});
Server Logging
如果定义了 log
方法,它将使用“received”和“replied”调用 连同数据。
server = soap.listen(...)
server.log = function(type, data) {
// type is 'received' or 'replied'
};
Server Events
服务器实例发出以下事件:
- request - Emitted for every received messages. The signature of the callback is
function(request, methodName)
. - headers - Emitted when the SOAP Headers are not empty. The signature of the callback is
function(headers, methodName)
.
调用的顺序是 request
、headers
然后是专用的 服务方式。
Server Response on one-way calls
当在 WSDL 中没有定义输出的情况下调用操作时,就会发生所谓的单向(或异步)调用。 服务器向客户端发送响应(默认为状态代码 200,无正文),忽略操作结果。
您可以配置响应以将适当的客户端期望与 SOAP 标准实现相匹配。 在服务器选项中传入 oneWay
对象。 使用以下键: emptyBody
:如果为 true,则返回一个空主体,否则根本没有内容(默认为 false) responseCode
:默认 statusCode 为 200,使用此选项覆盖它(例如 202 用于符合 SAP 标准
SOAP Fault
的响应)服务方法可以通过 throw
向客户端回复 SOAP Fault正在 具有 Fault
属性的对象。
throw {
Fault: {
Code: {
Value: 'soap:Sender',
Subcode: { value: 'rpc:BadArguments' }
},
Reason: { Text: 'Processing Error' }
}
};
要更改响应的 HTTP statusCode,请将其包含在故障中。 statusCode 属性不会放在 xml 消息上。
throw {
Fault: {
Code: {
Value: 'soap:Sender',
Subcode: { value: 'rpc:BadArguments' }
},
Reason: { Text: 'Processing Error' },
statusCode: 500
}
};
Server security example using PasswordDigest
如果未定义 server.authenticate
,则不会进行身份验证。
异步身份验证:
server = soap.listen(...)
server.authenticate = function(security, callback) {
var created, nonce, password, user, token;
token = security.UsernameToken, user = token.Username,
password = token.Password, nonce = token.Nonce, created = token.Created;
myDatabase.getUser(user, function (err, dbUser) {
if (err || !dbUser) {
callback(false);
return;
}
callback(password === soap.passwordDigest(nonce, created, dbUser.password));
});
};
同步身份验证:
server = soap.listen(...)
server.authenticate = function(security) {
var created, nonce, password, user, token;
token = security.UsernameToken, user = token.Username,
password = token.Password, nonce = token.Nonce, created = token.Created;
return user === 'user' && password === soap.passwordDigest(nonce, created, 'password');
};
Server connection authorization
server.authorizeConnection
方法在 soap 服务方法之前被调用。 如果方法已定义并返回 false
则传入连接是 终止。
server = soap.listen(...)
server.authorizeConnection = function(req) {
return true; // or false
};
SOAP Headers
Received SOAP Headers
服务方法可以通过提供第三个参数来查看 SOAP 标头。
{
HeadersAwareFunction: function(args, cb, headers) {
return {
name: headers.Token
};
}
}
也可以订阅 'headers' 事件。 该事件在调用服务方法之前触发,并且仅当 SOAP 标头不为空。
server = soap.listen(...)
server.on('headers', function(headers, methodName) {
// It is possible to change the value of the headers
// before they are handed to the service method.
// It is also possible to throw a SOAP Fault
});
第一个参数是 Headers 对象; 第二个参数是将调用的 SOAP 方法的名称 (以防您需要根据方法以不同方式处理标头)。
Outgoing SOAP Headers
客户和客户 服务器可以定义将添加到它们发送的内容中的 SOAP 标头。 它们提供了以下方法来管理标头。
addSoapHeader(soapHeader[, name, namespace, xmlns]) - add soapHeader to soap:Header node
Parameters
soapHeader
Object({rootName: {name: 'value'}}), strict xml-string, or function (server only)
仅对于服务器,soapHeader
可以是一个函数,它允许标头是 根据请求中的信息动态生成。 这个功能将是 为每个收到的请求调用以下参数:
methodName
The name of the request methodargs
The arguments of the requestheaders
The headers in the requestreq
The original request object
函数的返回值必须是一个对象({rootName:{name:'value'}}) 或严格的 xml 字符串,它将作为 对该请求的回应。
例如:
server = soap.listen(...);
server.addSoapHeader(function(methodName, args, headers, req) {
console.log('Adding headers for method', methodName);
return {
MyHeader1: args.SomeValueFromArgs,
MyHeader2: headers.SomeRequestHeader
};
// or you can return "<MyHeader1>SomeValue</MyHeader1>"
});
Returns
插入标头的索引。
Optional parameters when first arg is object :
name
Unknown parameter (it could just a empty string)namespace
prefix of xml namespacexmlns
URI
changeSoapHeader(index, soapHeader[, name, namespace, xmlns]) - change an already existing soapHeader
Parameters
index
index of the header to replace with provided new valuesoapHeader
Object({rootName: {name: 'value'}}), strict xml-string or function (server only)
有关如何将函数传递到 soapHeader
的信息,请参见 addSoapHeader
。
getSoapHeaders() - return all defined headers
clearSoapHeaders() - remove all defined headers
Client
Client
的一个实例被传递给 soap.createClient
回调。 它用于在 soap 服务上执行方法。
Client.describe() - description of services, ports and methods as a JavaScript object
client.describe() // returns
{
MyService: {
MyPort: {
MyFunction: {
input: {
name: 'string'
}
}
}
}
}
Client.setSecurity(security) - use the specified security protocol
Client.method(args, callback, options) - call method on the SOAP service.
client.MyFunction({name: 'value'}, function(err, result, rawResponse, soapHeader, rawRequest) {
// result is a javascript object
// rawResponse is the raw xml response string
// soapHeader is the response soap header as a javascript object
// rawRequest is the raw xml request string
})
args
参数允许您提供在 SOAP 主体部分内生成 XML 文档的参数。
options
对象是可选的,它被传递给 request
模块。 有趣的属性可能是:
timeout
: Timeout in millisecondsforever
: Enables keep-alive connections and pools them
Client.methodAsync(args) - call method on the SOAP service.
client.MyFunctionAsync({name: 'value'}).then((result) => {
// result is a javascript array containing result, rawResponse, soapheader, and rawRequest
// result is a javascript object
// rawResponse is the raw xml response string
// soapHeader is the response soap header as a javascript object
// rawRequest is the raw xml request string
})
args
参数允许您提供在 SOAP Body 部分内生成 XML 文档的参数。
Example with JSON for the args
上面的示例使用 {name: 'value'}
作为参数。 这可能会生成一条 SOAP 消息,例如:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<Request xmlns="http://www.example.com/v1">
<name>value</name>
</Request>
</soapenv:Body>
</soapenv:Envelope>
请注意,上面输出中的“Request”元素来自 WSDL。 如果 args
中的元素不包含名称空间前缀,则假定为默认名称空间。 否则,您必须根据需要将名称空间前缀添加到元素名称(例如,ns1:name
)。
目前,在提供 JSON args 时,元素不能同时包含子元素和文本值,即使 XML 规范允许这样做。
Example with XML String for the args
您可以传入完整格式的 XML 字符串,而不是 JSON args
中的各个元素和构成 XML 的属性。 XML 字符串不应包含 XML 声明(例如,)或文档类型声明(例如,
)。
var args = { _xml: "<ns1:MyRootElement xmlns:ns1="http://www.example.com/v1/ns1">
<ChildElement>elementvalue</ChildElement>
</ns1:MyRootElement>"
};
您必须自己指定所有名称空间和名称空间前缀。 WSDL 中的元素未被使用,因为它们在上面的“使用 JSON 作为 args
的示例”示例中使用,该示例自动填充了“Request”元素。
Client.service.port.method(args, callback[, options[, extraHeaders]]) - call a method using a specific service and port
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// result is a javascript object
})
Options (optional)
- Accepts any option that the request module accepts, see here.
- For example, you could set a timeout of 5 seconds on the request like this:
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// result is a javascript object
}, {timeout: 5000})
- You can measure the elapsed time on the request by passing the time option:
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {time: true})
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {proxy: 'http://localhost:8888'})
- You can modify xml (string) before call:
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {postProcess: function(_xml) {
return _xml.replace('text', 'newtext');
}})
Extra Headers (optional)
对象属性定义要在请求中发送的额外 HTTP 标头。
- Add custom User-Agent:
client.addHttpHeader('User-Agent', `CustomUserAgent`);
Alternative method call using callback-last pattern
为了使方法调用签名与节点的标准回调最后模式和事件允许方法调用的 promisification 保持一致,还支持以下方法签名:
client.MyService.MyPort.MyFunction({name: 'value'}, options, function (err, result) {
// result is a javascript object
})
client.MyService.MyPort.MyFunction({name: 'value'}, options, extraHeaders, function (err, result) {
// result is a javascript object
})
Overriding the namespace prefix
node-soap
仍在解决有关命名空间的一些问题。 如果您发现某个元素在请求正文中给出了错误的命名空间前缀,您可以将前缀添加到包含对象中的名称中。 IE:
client.MyService.MyPort.MyFunction({'ns1:name': 'value'}, function(err, result) {
// request body sent with `<ns1:name`, regardless of what the namespace should have been.
}, {timeout: 5000})
- Remove namespace prefix of param
client.MyService.MyPort.MyFunction({':name': 'value'}, function(err, result) {
// request body sent with `<name`, regardless of what the namespace should have been.
}, {timeout: 5000})
Client.lastRequest - the property that contains last full soap request for client logging
Client.setEndpoint(url) - overwrite the SOAP service endpoint address
Client Events
客户端实例发出以下事件:
request
在发送请求之前发出。 事件处理程序具有签名 (xml, eid)
。
- xml - The entire Soap request (Envelope) including headers.
- eid - The exchange id.
message
在发送请求之前发出,但仅将正文传递给事件处理程序。 如果您不想记录/存储 Soap 标头,则很有用。 事件处理程序具有签名 (message, eid)
。
- message - Soap body contents.
- eid - The exchange id.
soapError
收到错误响应时发出。 如果您想全局记录错误,则很有用。 事件处理程序具有签名 (error, eid)
。
- error - An error object which also contains the resoponse.
- eid - The exchange id.
response
收到响应后发出。 这是针对所有响应(成功和错误)发出的。 事件处理程序具有签名 (body, response, eid)
- body - The SOAP response body.
- response - The entire
IncomingMessage
response object. - eid - The exchange id.
“交换”是一对请求/响应。 事件处理程序在所有事件中接收交换 ID。 请求事件和响应事件的交换 ID 相同,这样您就可以使用它来检索匹配的请求 当收到响应事件时。
默认情况下,交换 ID 是使用 node-uuid 生成的,但您可以在客户端调用中使用选项来传递您自己的交换 ID。
示例:
client.MyService.MyPort.MyFunction(args , function(err, result) {
}, {exchangeId: myExchangeId})
Security
node-soap
有几个默认的安全协议。 您可以轻松添加自己的 以及。 界面非常简单。 每个协议都定义了这些可选方法:
addOptions(options)
- a method that accepts an options arg that is eventually passed directly torequest
.addHeaders(headers)
- a method that accepts an argument with HTTP headers, to add new ones.toXML()
- a method that returns a string of XML to be appended to the SOAP headers. Not executed ifpostProcess
is also defined.postProcess(xml, envelopeKey)
- a method that receives the the assembled request XML plus envelope key, and returns a processed string of XML. Executed beforeoptions.postProcess
.
BasicAuthSecurity
client.setSecurity(new soap.BasicAuthSecurity('username', 'password'));
BearerSecurity
client.setSecurity(new soap.BearerSecurity('token'));
ClientSSLSecurity
注意:如果您在使用此协议时遇到问题,请考虑传递这些选项 作为构造函数的默认请求选项:
rejectUnauthorized: false
strictSSL: false
secureOptions: constants.SSL_OP_NO_TLSv1_2
(this is likely needed for node >= 10.0)
如果你想重用 tls 会话,你可以使用选项 forever: true
。
client.setSecurity(new soap.ClientSSLSecurity(
'/path/to/key',
'path/to/cert',
'/path/to/ca-cert', /*or an array of buffer: [fs.readFileSync('/path/to/ca-cert/1', 'utf8'),
'fs.readFileSync('/path/to/ca-cert/2', 'utf8')], */
{ /*default request options like */
// strictSSL: true,
// rejectUnauthorized: false,
// hostname: 'some-hostname'
// secureOptions: constants.SSL_OP_NO_TLSv1_2,
// forever: true,
},
));
ClientSSLSecurityPFX
注意:如果您在使用此协议时遇到问题,请考虑传递这些选项 作为构造函数的默认请求选项:
rejectUnauthorized: false
strictSSL: false
secureOptions: constants.SSL_OP_NO_TLSv1_2
(this is likely needed for node >= 10.0)
如果你想重用 tls 会话,你可以使用选项 forever: true
。
client.setSecurity(new soap.ClientSSLSecurityPFX(
'/path/to/pfx/cert', // or a buffer: [fs.readFileSync('/path/to/pfx/cert', 'utf8'),
'path/to/optional/passphrase',
{ /*default request options like */
// strictSSL: true,
// rejectUnauthorized: false,
// hostname: 'some-hostname'
// secureOptions: constants.SSL_OP_NO_TLSv1_2,
// forever: true,
},
));
WSSecurity
WSSecurity
实现 WS-Security。 支持 UsernameToken 和 PasswordText/PasswordDigest。
var options = {
hasNonce: true,
actor: 'actor'
};
var wsSecurity = new soap.WSSecurity('username', 'password', options)
client.setSecurity(wsSecurity);
options
对象是可选的,可以包含以下属性:
passwordType
: 'PasswordDigest' or 'PasswordText' (default:'PasswordText'
)hasTimeStamp
: adds Timestamp element (default:true
)hasTokenCreated
: adds Created element (default:true
)hasNonce
: adds Nonce element (default:false
)mustUnderstand
: adds mustUnderstand=1 attribute to security tag (default:false
)actor
: if set, adds Actor attribute with given value to security tag (default:''
)
WSSecurityCert
WS-Security X509 证书支持。
var privateKey = fs.readFileSync(privateKeyPath);
var publicKey = fs.readFileSync(publicKeyPath);
var password = ''; // optional password
var wsSecurity = new soap.WSSecurityCert(privateKey, publicKey, password);
client.setSecurity(wsSecurity);
NTLMSecurity
参数调用:
client.setSecurity(new soap.NTLMSecurity('username', 'password', 'domain', 'workstation'));
这也可以用JSON对象来设置,根据需要替换值,例如:
var loginData = {username: 'username', password: 'password', domain: 'domain', workstation: 'workstation'};
client.setSecurity(new soap.NTLMSecurity(loginData));
Handling XML Attributes, Value and XML (wsdlOptions).
有时需要覆盖node-soap
的默认行为以处理特殊需求 您的代码库或您使用的第三个库。 因此,您可以使用 wsdlOptions
对象,它在 #createClient()
方法,并且可以具有以下任何(或全部)内容:
var wsdlOptions = {
attributesKey: 'theAttrs',
valueKey: 'theVal',
xmlKey: 'theXml'
}
如果没有(或空对象 {}
)传递给 # createClient()
方法,node-soap
默认值(attributesKey: 'attributes'
, valueKey: '$value'
和 < code>xmlKey: '$xml') 被使用。
Overriding the value
key
默认情况下,node-soap
使用 $value
作为任何已解析的 XML 值的键,这可能会干扰您的其他代码,因为它 可能是一些保留字,或者 $
通常不能用作开始的键。
您可以通过将 wsdl_options
传递给 createClient 调用来定义自己的 valueKey
:
var wsdlOptions = {
valueKey: 'theVal'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
// your code
});
Overriding the xml
key
默认情况下,node-soap
使用 $xml
作为传递 XML 字符串的键; 无需解析或命名空间。 它覆盖节点可能拥有的所有其他内容。
例如:
{
dom: {
nodeone: {
$xml: '<parentnode type="type"><childnode></childnode></parentnode>',
siblingnode: 'Cant see me.'
},
nodetwo: {
parentnode: {
attributes: {
type: 'type'
},
childnode: ''
}
}
}
};
可以成为
<tns:dom>
<tns:nodeone>
<parentnode type="type">
<childnode></childnode>
</parentnode>
</tns:nodeone>
<tns:nodetwo>
<tns:parentnode type="type">
<tns:childnode></tns:childnode>
</tns:parent>
</tns:nodetwo>
</tns:dom>
您可以通过将 wsdl_options
对象传递给 createClient 调用来定义您自己的 xmlKey
:
var wsdlOptions = {
xmlKey: 'theXml'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
// your code
});
Overriding the attributes
key
默认情况下,node-soap
使用 attributes
作为定义节点属性的键。
{
parentnode: {
childnode: {
attributes: {
name: 'childsname'
},
$value: 'Value'
}
}
}
可能会变成
<parentnode>
<childnode name="childsname">Value</childnode>
</parentnode>
但是,attributes
可能是某些系统的保留键,这些系统实际上需要一个名为 attributes
的节点
<attributes>
</attributes>
您可以通过传递它来定义自己的 attributesKey
在 wsdl_options
对象中调用 createClient:
var wsdlOptions = {
attributesKey: '$attributes'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
client.method({
parentnode: {
childnode: {
$attributes: {
name: 'childsname'
},
$value: 'Value'
}
}
});
});
Specifying the exact namespace definition of the root element
在极少数情况下,您可能希望精确控制包含在根元素中的命名空间定义。
您可以通过在 wsdlOptions
中设置 overrideRootElement
键来指定名称空间定义,如下所示:
var wsdlOptions = {
overrideRootElement: {
namespace: 'xmlns:tns',
xmlnsAttributes: [{
name: 'xmlns:ns2',
value: "http://tempuri.org/"
}, {
name: 'xmlns:ns3',
value: "http://sillypets.com/xsd"
}]
}
};
要在实践中看到它,请查看示例文件:test/request-response-samples/addPets_force命名空间
Custom Deserializer
有时在代码中处理反序列化而不是让 node-soap 来处理反序列化很有用。 例如,如果 soap 响应包含 javascript 无法识别的格式的日期,您可能希望使用自己的函数来处理它们。
为此,您可以在 options
中传递一个 customDeserializer
对象。 该对象的属性是反序列化器自行处理的类型。
示例:
var wsdlOptions = {
customDeserializer: {
// this function will be used to any date found in soap responses
date: function (text, context) {
/* text is the value of the xml element.
context contains the name of the xml element and other infos :
{
name: 'lastUpdatedDate',
object: {},
schema: 'xsd:date',
id: undefined,
nil: false
}
*/
return text;
}
}
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
...
});
Changing the tag formats to use self-closing (empty element) tags
XML规范规定
和
之间没有语义差异,node-soap默认为使用
格式。 但是,如果您的 Web 服务是特殊的,或者如果有风格偏好,useEmptyTag
选项会导致没有内容的标签改用
格式。
var wsdlOptions = {
useEmptyTag: true
};
例如:{ MyTag: { attributes: { MyAttr: 'value' } } }
是:
- Without useEmptyTag:
<MyTag MyAttr="value"></MyTag>
- With useEmptyTag set to true:
<MyTag MyAttr="value" />
Handling "ignored" namespaces
如果 schema
定义中的元素依赖于存在于相同的命名空间,通常是 tns:
名称空间前缀用于标识此元素。 只要您只定义了一个 schema
,这就不是什么大问题 (内联或在单独的文件中)。 如果有更多的 schema
文件,生成的 soap
文件中的 tns:
大部分解析为父 wsdl
文件, 这显然是错误的。
node-soap
现在处理名称空间前缀,这些前缀不应被解析(因为它不是必需的),因为所谓的 ignoredNamespaces
默认为 3 个字符串的数组 (['tns', 'targetNamespace', 'typedNamespace']
)。
如果这不足以满足您的目的,您可以轻松地向此数组添加更多名称空间前缀,或完全覆盖它 通过在 options
中传递一个 ignoredNamespaces
对象,您传入 soap.createClient()
方法。
一个简单的 ignoredNamespaces
对象,它只添加某些命名空间可能看起来像这样:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace']
}
}
这会将 WSDL
处理器的 ignoredNamespaces
扩展到 [ 'tns', 'targetNamespace', 'typedNamespace', 'namespaceToIgnore', 'someOtherNamespace']
。
如果您想覆盖默认的忽略命名空间,您只需在 options
中传递以下 ignoredNamespaces
对象:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
override: true
}
}
这将覆盖默认的 ignoredNamespaces
WSDL
处理器到 ['namespaceToIgnore', 'someOtherNamespace']
。 (无论如何,这应该不是必需的)。
如果您想覆盖默认的忽略命名空间,您只需在 options
中传递以下 ignoredNamespaces
对象:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
override: true
}
}
这将覆盖默认的 ignoredNamespaces
WSDL
处理器到 ['namespaceToIgnore', 'someOtherNamespace']
。 (无论如何,这应该不是必需的)。
Handling "ignoreBaseNameSpaces" attribute
如果 schema
定义中的元素定义了一个基本命名空间,但请求不需要该值,例如,您有一个带有基本命名空间“v20”的“sentJob” 但请求只需要:
默认情况下,该属性设置为 true。 使用示例:
一个简单的 ignoredNamespaces
对象,它只添加特定的命名空间,可能如下所示:
var options = {
ignoredNamespaces: true
}
soap-stub
使用 soap 客户端的单元测试服务可能非常麻烦。 为了得到 围绕这个你可以使用 soap-stub
结合 sinon
来存根肥皂 你的客户。
Example
// test-initialization-script.js
var sinon = require('sinon');
var soapStub = require('soap/soap-stub');
var urlMyApplicationWillUseWithCreateClient = 'http://path-to-my-wsdl';
var clientStub = {
SomeOperation: sinon.stub()
};
clientStub.SomeOperation.respondWithError = soapStub.createErroringStub({..error json...});
clientStub.SomeOperation.respondWithSuccess = soapStub.createRespondingStub({..success json...});
soapStub.registerClient('my client alias', urlMyApplicationWillUseWithCreateClient, clientStub);
// test.js
var soapStub = require('soap/soap-stub');
describe('myService', function() {
var clientStub;
var myService;
beforeEach(function() {
clientStub = soapStub.getStub('my client alias');
soapStub.reset();
myService.init(clientStub);
});
describe('failures', function() {
beforeEach(function() {
clientStub.SomeOperation.respondWithError();
});
it('should handle error responses', function() {
myService.somethingThatCallsSomeOperation(function(err, response) {
// handle the error response.
});
});
});
});
Contributors
- Author: Vinay Pulim
- Maintainers:
- Joe Spencer
- Heinz Romirer
- All Contributors
Soap
A SOAP client and server for node.js.
This module lets you connect to web services using SOAP. It also provides a server that allows you to run your own SOAP services.
- Features:
- Install
- Why can't I file an issue?
- Where can I find help?
- Module
- soap.createClient(url[, options], callback) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
- soap.createClientAsync(url[, options]) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
- soap.listen(server, path, services, wsdl) - create a new SOAP server that listens on path and provides services.
- Options
- Server Logging
- Server Events
- Server Response on one-way calls
- SOAP Fault
- Server security example using PasswordDigest
- Server connection authorization
- SOAP Headers
- Received SOAP Headers
- Outgoing SOAP Headers
- Client
- Client.describe() - description of services, ports and methods as a JavaScript object
- Client.setSecurity(security) - use the specified security protocol
- Client.method(args, callback) - call method on the SOAP service.
- Client.methodAsync(args) - call method on the SOAP service.
- [Client.service.port.method(args, callback[, options[, extraHeaders]]) - call a method using a specific service and port](#clientserviceportmethodargs-callback-options-extraheaders---call-a-method-using-a-specific-service-and-port)
- Overriding the namespace prefix
- Client.lastRequest - the property that contains last full soap request for client logging
- Client.setEndpoint(url) - overwrite the SOAP service endpoint address
- Client Events
- Security
- BasicAuthSecurity
- BearerSecurity
- ClientSSLSecurity
- ClientSSLSecurityPFX
- WSSecurity
- WSSecurityCert
- NTLMSecurity
- Handling XML Attributes, Value and XML (wsdlOptions).
- Overriding the
value
key - Overriding the
xml
key - Overriding the
attributes
key - Specifying the exact namespace definition of the root element
- Custom Deserializer
- Handling "ignored" namespaces
- Handling "ignoreBaseNameSpaces" attribute
- soap-stub
- Example
- Contributors
Features:
- Very simple API
- Handles both RPC and Document schema types
- Supports multiRef SOAP messages (thanks to @kaven276)
- Support for both synchronous and asynchronous method handlers
- WS-Security (currently only UsernameToken and PasswordText encoding is supported)
- Supports express based web server(body parser middleware can be used)
Install
Install with npm:
npm install soap
Why can't I file an issue?
We've disabled issues in the repository and are now solely reviewing pull requests. The reasons why we disabled issues can be found here #731.
Where can I find help?
Community support can be found on gitter:
If you're looking for professional help you can contact the maintainers through this google form.
Module
soap.createClient(url[, options], callback) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClient(url, function(err, client) {
client.MyFunction(args, function(err, result) {
console.log(result);
});
});
This client has a built in WSDL cache. You can use the disableCache
option to disable it.
soap.createClientAsync(url[, options]) - create a new SOAP client from a WSDL url. Also supports a local filesystem path.
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClientAsync(url).then((client) => {
return client.MyFunctionAsync(args);
}).then((result) => {
console.log(result);
});
This client has a built in WSDL cache. You can use the disableCache
option to disable it.
Options
The options
argument allows you to customize the client with the following properties:
- endpoint: to override the SOAP service's host specified in the
.wsdl
file. - envelopeKey: to set specific key instead of
<pre><soap:Body></soap:Body></pre>
. - preserveWhitespace: to preserve leading and trailing whitespace characters in text and cdata.
- escapeXML: escape special XML characters in SOAP message (e.g.
&
,>
,<
etc), default:true
. - suppressStack: suppress the full stack trace for error messages.
- returnFault: return an
Invalid XML
SOAP fault on a bad request, default:false
. - forceSoap12Headers: to set proper headers for SOAP v1.2.
- httpClient: to provide your own http client that implements
request(rurl, data, callback, exheaders, exoptions)
. - request: to override the request module.
- wsdl_headers: custom HTTP headers to be sent on WSDL requests.
- wsdl_options: custom options for the request module on WSDL requests.
- disableCache: don't cache WSDL files, request them every time.
- overridePromiseSuffix: if your wsdl operations contains names with Async suffix, you will need to override the default promise suffix to a custom one, default:
Async
. - normalizeNames: if your wsdl operations contains names with non identifier characters (
[^a-z$_0-9]
), replace them with_
. Note: if using this option, clients using wsdls with two operations likesoap:method
andsoap-method
will be overwritten. Then, use bracket notation instead (client['soap:method']()
). - namespaceArrayElements: provides support for nonstandard array semantics. If true, JSON arrays of the form
{list: [{elem: 1}, {elem: 2}]}
are marshalled into xml as<list><elem>1</elem></list> <list><elem>2</elem></list>
. If false, marshalls into<list> <elem>1</elem> <elem>2</elem> </list>
. Default:true
.
Note: for versions of node >0.10.X, you may need to specify {connection: 'keep-alive'}
in SOAP headers to avoid truncation of longer chunked responses.
soap.listen(server, path, services, wsdl) - create a new SOAP server that listens on path and provides services.
server can be a http Server or express framework based server wsdl is an xml string that defines the service.
var myService = {
MyService: {
MyPort: {
MyFunction: function(args) {
return {
name: args.name
};
},
// This is how to define an asynchronous function with a callback.
MyAsyncFunction: function(args, callback) {
// do some work
callback({
name: args.name
});
},
// This is how to define an asynchronous function with a Promise.
MyPromiseFunction: function(args) {
return new Promise((resolve) => {
// do some work
resolve({
name: args.name
});
});
},
// This is how to receive incoming headers
HeadersAwareFunction: function(args, cb, headers) {
return {
name: headers.Token
};
},
// You can also inspect the original `req`
reallyDetailedFunction: function(args, cb, headers, req) {
console.log('SOAP `reallyDetailedFunction` request from ' + req.connection.remoteAddress);
return {
name: headers.Token
};
}
}
}
};
var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
//http server example
var server = http.createServer(function(request,response) {
response.end('404: Not Found: ' + request.url);
});
server.listen(8000);
soap.listen(server, '/wsdl', myService, xml);
//express server example
var app = express();
//body parser middleware are supported (optional)
app.use(bodyParser.raw({type: function(){return true;}, limit: '5mb'}));
app.listen(8001, function(){
//Note: /wsdl route will be handled by soap module
//and all other routes & middleware will continue to work
soap.listen(app, '/wsdl', myService, xml);
});
Options
You can pass in server and WSDL Options using an options hash.
Server options include the below:
pfx
: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the key, cert and ca options.)key
: A string or Buffer containing the private key of the server in PEM format. (Could be an array of keys). (Required)passphrase
: A string of passphrase for the private key or pfx.cert
: A string or Buffer containing the certificate key of the server in PEM format. (Could be an array of certs). (Required)ca
: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.crl
: Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)ciphers
: A string describing the ciphers to use or exclude, separated by :. The default cipher suite is:enableChunkedEncoding
: A boolean for controlling chunked transfer encoding in response. Some client (such as Windows 10's MDM enrollment SOAP client) is sensitive to transfer-encoding mode and can't accept chunked response. This option let user disable chunked transfer encoding for such a client. Default totrue
for backward compatibility.
var xml = require('fs').readFileSync('myservice.wsdl', 'utf8');
soap.listen(server, {
// Server options.
path: '/wsdl',
services: myService,
xml: xml,
// WSDL options.
attributesKey: 'theAttrs',
valueKey: 'theVal',
xmlKey: 'theXml'
});
Server Logging
If the log
method is defined it will be called with 'received' and 'replied' along with data.
server = soap.listen(...)
server.log = function(type, data) {
// type is 'received' or 'replied'
};
Server Events
Server instances emit the following events:
- request - Emitted for every received messages. The signature of the callback is
function(request, methodName)
. - headers - Emitted when the SOAP Headers are not empty. The signature of the callback is
function(headers, methodName)
.
The sequence order of the calls is request
, headers
and then the dedicated service method.
Server Response on one-way calls
The so called one-way (or asynchronous) calls occur when an operation is called with no output defined in WSDL. The server sends a response (defaults to status code 200 with no body) to the client disregarding the result of the operation.
You can configure the response to match the appropriate client expectation to the SOAP standard implementation. Pass in oneWay
object in server options. Use the following keys: emptyBody
: if true, returns an empty body, otherwise no content at all (default is false) responseCode
: default statusCode is 200, override it with this options (for example 202 for SAP standard compliant response)
SOAP Fault
A service method can reply with a SOAP Fault to a client by throw
ing an object with a Fault
property.
throw {
Fault: {
Code: {
Value: 'soap:Sender',
Subcode: { value: 'rpc:BadArguments' }
},
Reason: { Text: 'Processing Error' }
}
};
To change the HTTP statusCode of the response include it on the fault. The statusCode property will not be put on the xml message.
throw {
Fault: {
Code: {
Value: 'soap:Sender',
Subcode: { value: 'rpc:BadArguments' }
},
Reason: { Text: 'Processing Error' },
statusCode: 500
}
};
Server security example using PasswordDigest
If server.authenticate
is not defined then no authentication will take place.
Asynchronous authentication:
server = soap.listen(...)
server.authenticate = function(security, callback) {
var created, nonce, password, user, token;
token = security.UsernameToken, user = token.Username,
password = token.Password, nonce = token.Nonce, created = token.Created;
myDatabase.getUser(user, function (err, dbUser) {
if (err || !dbUser) {
callback(false);
return;
}
callback(password === soap.passwordDigest(nonce, created, dbUser.password));
});
};
Synchronous authentication:
server = soap.listen(...)
server.authenticate = function(security) {
var created, nonce, password, user, token;
token = security.UsernameToken, user = token.Username,
password = token.Password, nonce = token.Nonce, created = token.Created;
return user === 'user' && password === soap.passwordDigest(nonce, created, 'password');
};
Server connection authorization
The server.authorizeConnection
method is called prior to the soap service method. If the method is defined and returns false
then the incoming connection is terminated.
server = soap.listen(...)
server.authorizeConnection = function(req) {
return true; // or false
};
SOAP Headers
Received SOAP Headers
A service method can look at the SOAP headers by providing a 3rd arguments.
{
HeadersAwareFunction: function(args, cb, headers) {
return {
name: headers.Token
};
}
}
It is also possible to subscribe to the 'headers' event. The event is triggered before the service method is called, and only when the SOAP Headers are not empty.
server = soap.listen(...)
server.on('headers', function(headers, methodName) {
// It is possible to change the value of the headers
// before they are handed to the service method.
// It is also possible to throw a SOAP Fault
});
First parameter is the Headers object; second parameter is the name of the SOAP method that will called (in case you need to handle the headers differently based on the method).
Outgoing SOAP Headers
Both client & server can define SOAP headers that will be added to what they send. They provide the following methods to manage the headers.
addSoapHeader(soapHeader[, name, namespace, xmlns]) - add soapHeader to soap:Header node
Parameters
soapHeader
Object({rootName: {name: 'value'}}), strict xml-string, or function (server only)
For servers only, soapHeader
can be a function, which allows headers to be dynamically generated from information in the request. This function will be called with the following arguments for each received request:
methodName
The name of the request methodargs
The arguments of the requestheaders
The headers in the requestreq
The original request object
The return value of the function must be an Object({rootName: {name: 'value'}}) or strict xml-string, which will be inserted as an outgoing header of the response to that request.
For example:
server = soap.listen(...);
server.addSoapHeader(function(methodName, args, headers, req) {
console.log('Adding headers for method', methodName);
return {
MyHeader1: args.SomeValueFromArgs,
MyHeader2: headers.SomeRequestHeader
};
// or you can return "<MyHeader1>SomeValue</MyHeader1>"
});
Returns
The index where the header is inserted.
Optional parameters when first arg is object :
name
Unknown parameter (it could just a empty string)namespace
prefix of xml namespacexmlns
URI
changeSoapHeader(index, soapHeader[, name, namespace, xmlns]) - change an already existing soapHeader
Parameters
index
index of the header to replace with provided new valuesoapHeader
Object({rootName: {name: 'value'}}), strict xml-string or function (server only)
See addSoapHeader
for how to pass a function into soapHeader
.
getSoapHeaders() - return all defined headers
clearSoapHeaders() - remove all defined headers
Client
An instance of Client
is passed to the soap.createClient
callback. It is used to execute methods on the soap service.
Client.describe() - description of services, ports and methods as a JavaScript object
client.describe() // returns
{
MyService: {
MyPort: {
MyFunction: {
input: {
name: 'string'
}
}
}
}
}
Client.setSecurity(security) - use the specified security protocol
Client.method(args, callback, options) - call method on the SOAP service.
client.MyFunction({name: 'value'}, function(err, result, rawResponse, soapHeader, rawRequest) {
// result is a javascript object
// rawResponse is the raw xml response string
// soapHeader is the response soap header as a javascript object
// rawRequest is the raw xml request string
})
The args
argument allows you to supply arguments that generate an XML document inside of the SOAP Body section.
The options
object is optional and is passed to the request
-module. Interesting properties might be:
timeout
: Timeout in millisecondsforever
: Enables keep-alive connections and pools them
Client.methodAsync(args) - call method on the SOAP service.
client.MyFunctionAsync({name: 'value'}).then((result) => {
// result is a javascript array containing result, rawResponse, soapheader, and rawRequest
// result is a javascript object
// rawResponse is the raw xml response string
// soapHeader is the response soap header as a javascript object
// rawRequest is the raw xml request string
})
The args
argument allows you to supply arguments that generate an XML document inside of the SOAP Body section.
Example with JSON for the args
The example above uses {name: 'value'}
as the args. This may generate a SOAP messages such as:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<Request xmlns="http://www.example.com/v1">
<name>value</name>
</Request>
</soapenv:Body>
</soapenv:Envelope>
Note that the "Request" element in the output above comes from the WSDL. If an element in args
contains no namespace prefix, the default namespace is assumed. Otherwise, you must add the namespace prefixes to the element names as necessary (e.g., ns1:name
).
Currently, when supplying JSON args, elements may not contain both child elements and a text value, even though that is allowed in the XML specification.
Example with XML String for the args
You may pass in a fully-formed XML string instead the individual elements in JSON args
and attributes that make up the XML. The XML string should not contain an XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>
) or a document type declaration (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
).
var args = { _xml: "<ns1:MyRootElement xmlns:ns1="http://www.example.com/v1/ns1">
<ChildElement>elementvalue</ChildElement>
</ns1:MyRootElement>"
};
You must specify all of the namespaces and namespace prefixes yourself. The element(s) from the WSDL are not utilized as they were in the "Example with JSON as the args
" example above, which automatically populated the "Request" element.
Client.service.port.method(args, callback[, options[, extraHeaders]]) - call a method using a specific service and port
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// result is a javascript object
})
Options (optional)
- Accepts any option that the request module accepts, see here.
- For example, you could set a timeout of 5 seconds on the request like this:
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// result is a javascript object
}, {timeout: 5000})
- You can measure the elapsed time on the request by passing the time option:
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {time: true})
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {proxy: 'http://localhost:8888'})
- You can modify xml (string) before call:
client.MyService.MyPort.MyFunction({name: 'value'}, function(err, result) {
// client.lastElapsedTime - the elapsed time of the last request in milliseconds
}, {postProcess: function(_xml) {
return _xml.replace('text', 'newtext');
}})
Extra Headers (optional)
Object properties define extra HTTP headers to be sent on the request.
- Add custom User-Agent:
client.addHttpHeader('User-Agent', `CustomUserAgent`);
Alternative method call using callback-last pattern
To align method call signature with node' standard callback-last patter and event allow promisification of method calls, the following method signatures are also supported:
client.MyService.MyPort.MyFunction({name: 'value'}, options, function (err, result) {
// result is a javascript object
})
client.MyService.MyPort.MyFunction({name: 'value'}, options, extraHeaders, function (err, result) {
// result is a javascript object
})
Overriding the namespace prefix
node-soap
is still working out some kinks regarding namespaces. If you find that an element is given the wrong namespace prefix in the request body, you can add the prefix to it's name in the containing object. I.E.:
client.MyService.MyPort.MyFunction({'ns1:name': 'value'}, function(err, result) {
// request body sent with `<ns1:name`, regardless of what the namespace should have been.
}, {timeout: 5000})
- Remove namespace prefix of param
client.MyService.MyPort.MyFunction({':name': 'value'}, function(err, result) {
// request body sent with `<name`, regardless of what the namespace should have been.
}, {timeout: 5000})
Client.lastRequest - the property that contains last full soap request for client logging
Client.setEndpoint(url) - overwrite the SOAP service endpoint address
Client Events
Client instances emit the following events:
request
Emitted before a request is sent. The event handler has the signature (xml, eid)
.
- xml - The entire Soap request (Envelope) including headers.
- eid - The exchange id.
message
Emitted before a request is sent, but only the body is passed to the event handler. Useful if you don't want to log /store Soap headers. The event handler has the signature (message, eid)
.
- message - Soap body contents.
- eid - The exchange id.
soapError
Emitted when an erroneous response is received. Useful if you want to globally log errors. The event handler has the signature (error, eid)
.
- error - An error object which also contains the resoponse.
- eid - The exchange id.
response
Emitted after a response is received. This is emitted for all responses (both success and errors). The event handler has the signature (body, response, eid)
- body - The SOAP response body.
- response - The entire
IncomingMessage
response object. - eid - The exchange id.
An 'exchange' is a request/response couple. Event handlers receive the exchange id in all events. The exchange id is the same for the requests events and the responses events, this way you can use it to retrieve the matching request when an response event is received.
By default exchange ids are generated by using node-uuid but you can use options in client calls to pass your own exchange id.
Example :
client.MyService.MyPort.MyFunction(args , function(err, result) {
}, {exchangeId: myExchangeId})
Security
node-soap
has several default security protocols. You can easily add your own as well. The interface is quite simple. Each protocol defines these optional methods:
addOptions(options)
- a method that accepts an options arg that is eventually passed directly torequest
.addHeaders(headers)
- a method that accepts an argument with HTTP headers, to add new ones.toXML()
- a method that returns a string of XML to be appended to the SOAP headers. Not executed ifpostProcess
is also defined.postProcess(xml, envelopeKey)
- a method that receives the the assembled request XML plus envelope key, and returns a processed string of XML. Executed beforeoptions.postProcess
.
BasicAuthSecurity
client.setSecurity(new soap.BasicAuthSecurity('username', 'password'));
BearerSecurity
client.setSecurity(new soap.BearerSecurity('token'));
ClientSSLSecurity
Note: If you run into issues using this protocol, consider passing these options as default request options to the constructor:
rejectUnauthorized: false
strictSSL: false
secureOptions: constants.SSL_OP_NO_TLSv1_2
(this is likely needed for node >= 10.0)
If you want to reuse tls sessions, you can use the option forever: true
.
client.setSecurity(new soap.ClientSSLSecurity(
'/path/to/key',
'path/to/cert',
'/path/to/ca-cert', /*or an array of buffer: [fs.readFileSync('/path/to/ca-cert/1', 'utf8'),
'fs.readFileSync('/path/to/ca-cert/2', 'utf8')], */
{ /*default request options like */
// strictSSL: true,
// rejectUnauthorized: false,
// hostname: 'some-hostname'
// secureOptions: constants.SSL_OP_NO_TLSv1_2,
// forever: true,
},
));
ClientSSLSecurityPFX
Note: If you run into issues using this protocol, consider passing these options as default request options to the constructor:
rejectUnauthorized: false
strictSSL: false
secureOptions: constants.SSL_OP_NO_TLSv1_2
(this is likely needed for node >= 10.0)
If you want to reuse tls sessions, you can use the option forever: true
.
client.setSecurity(new soap.ClientSSLSecurityPFX(
'/path/to/pfx/cert', // or a buffer: [fs.readFileSync('/path/to/pfx/cert', 'utf8'),
'path/to/optional/passphrase',
{ /*default request options like */
// strictSSL: true,
// rejectUnauthorized: false,
// hostname: 'some-hostname'
// secureOptions: constants.SSL_OP_NO_TLSv1_2,
// forever: true,
},
));
WSSecurity
WSSecurity
implements WS-Security. UsernameToken and PasswordText/PasswordDigest is supported.
var options = {
hasNonce: true,
actor: 'actor'
};
var wsSecurity = new soap.WSSecurity('username', 'password', options)
client.setSecurity(wsSecurity);
the options
object is optional and can contain the following properties:
passwordType
: 'PasswordDigest' or 'PasswordText' (default:'PasswordText'
)hasTimeStamp
: adds Timestamp element (default:true
)hasTokenCreated
: adds Created element (default:true
)hasNonce
: adds Nonce element (default:false
)mustUnderstand
: adds mustUnderstand=1 attribute to security tag (default:false
)actor
: if set, adds Actor attribute with given value to security tag (default:''
)
WSSecurityCert
WS-Security X509 Certificate support.
var privateKey = fs.readFileSync(privateKeyPath);
var publicKey = fs.readFileSync(publicKeyPath);
var password = ''; // optional password
var wsSecurity = new soap.WSSecurityCert(privateKey, publicKey, password);
client.setSecurity(wsSecurity);
NTLMSecurity
Parameter invocation:
client.setSecurity(new soap.NTLMSecurity('username', 'password', 'domain', 'workstation'));
This can also be set up with a JSON object, substituting values as appropriate, for example:
var loginData = {username: 'username', password: 'password', domain: 'domain', workstation: 'workstation'};
client.setSecurity(new soap.NTLMSecurity(loginData));
Handling XML Attributes, Value and XML (wsdlOptions).
Sometimes it is necessary to override the default behaviour of node-soap
in order to deal with the special requirements of your code base or a third library you use. Therefore you can use the wsdlOptions
Object, which is passed in the #createClient()
method and could have any (or all) of the following contents:
var wsdlOptions = {
attributesKey: 'theAttrs',
valueKey: 'theVal',
xmlKey: 'theXml'
}
If nothing (or an empty Object {}
) is passed to the #createClient()
method, the node-soap
defaults (attributesKey: 'attributes'
, valueKey: '$value'
and xmlKey: '$xml'
) are used.
Overriding the value
key
By default, node-soap
uses $value
as the key for any parsed XML value which may interfere with your other code as it could be some reserved word, or the $
in general cannot be used for a key to start with.
You can define your own valueKey
by passing it in the wsdl_options
to the createClient call:
var wsdlOptions = {
valueKey: 'theVal'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
// your code
});
Overriding the xml
key
By default, node-soap
uses $xml
as the key to pass through an XML string as is; without parsing or namespacing it. It overrides all the other content that the node might have otherwise had.
For example :
{
dom: {
nodeone: {
$xml: '<parentnode type="type"><childnode></childnode></parentnode>',
siblingnode: 'Cant see me.'
},
nodetwo: {
parentnode: {
attributes: {
type: 'type'
},
childnode: ''
}
}
}
};
could become
<tns:dom>
<tns:nodeone>
<parentnode type="type">
<childnode></childnode>
</parentnode>
</tns:nodeone>
<tns:nodetwo>
<tns:parentnode type="type">
<tns:childnode></tns:childnode>
</tns:parent>
</tns:nodetwo>
</tns:dom>
You can define your own xmlKey
by passing it in the wsdl_options
object to the createClient call:
var wsdlOptions = {
xmlKey: 'theXml'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
// your code
});
Overriding the attributes
key
By default, node-soap
uses attributes
as the key to define a nodes attributes.
{
parentnode: {
childnode: {
attributes: {
name: 'childsname'
},
$value: 'Value'
}
}
}
could become
<parentnode>
<childnode name="childsname">Value</childnode>
</parentnode>
However, attributes
may be a reserved key for some systems that actually want a node called attributes
<attributes>
</attributes>
You can define your own attributesKey
by passing it in the wsdl_options
object to the createClient call:
var wsdlOptions = {
attributesKey: '$attributes'
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
client.method({
parentnode: {
childnode: {
$attributes: {
name: 'childsname'
},
$value: 'Value'
}
}
});
});
Specifying the exact namespace definition of the root element
In rare cases, you may want to precisely control the namespace definition that is included in the root element.
You can specify the namespace definitions by setting the overrideRootElement
key in the wsdlOptions
like so:
var wsdlOptions = {
overrideRootElement: {
namespace: 'xmlns:tns',
xmlnsAttributes: [{
name: 'xmlns:ns2',
value: "http://tempuri.org/"
}, {
name: 'xmlns:ns3',
value: "http://sillypets.com/xsd"
}]
}
};
To see it in practice, have a look at the sample files in: test/request-response-samples/addPets_forcenamespaces
Custom Deserializer
Sometimes it's useful to handle deserialization in your code instead of letting node-soap do it. For example if the soap response contains dates that are not in a format recognized by javascript, you might want to use your own function to handle them.
To do so, you can pass a customDeserializer
object in options
. The properties of this object are the types that your deserializer handles itself.
Example :
var wsdlOptions = {
customDeserializer: {
// this function will be used to any date found in soap responses
date: function (text, context) {
/* text is the value of the xml element.
context contains the name of the xml element and other infos :
{
name: 'lastUpdatedDate',
object: {},
schema: 'xsd:date',
id: undefined,
nil: false
}
*/
return text;
}
}
};
soap.createClient(__dirname + '/wsdl/default_namespace.wsdl', wsdlOptions, function (err, client) {
...
});
Changing the tag formats to use self-closing (empty element) tags
The XML specification specifies that there is no semantic difference between <Tag></Tag>
and <Tag />
, and node-soap defaults to using the <Tag></Tag>
format. But if your web service is particular, or if there is a stylistic preference, the useEmptyTag
option causes tags with no contents to use the <Tag />
format instead.
var wsdlOptions = {
useEmptyTag: true
};
For example: { MyTag: { attributes: { MyAttr: 'value' } } }
is:
- Without useEmptyTag:
<MyTag MyAttr="value"></MyTag>
- With useEmptyTag set to true:
<MyTag MyAttr="value" />
Handling "ignored" namespaces
If an Element in a schema
definition depends on an Element which is present in the same namespace, normally the tns:
namespace prefix is used to identify this Element. This is not much of a problem as long as you have just one schema
defined (inline or in a separate file). If there are more schema
files, the tns:
in the generated soap
file resolved mostly to the parent wsdl
file, which was obviously wrong.
node-soap
now handles namespace prefixes which shouldn't be resolved (because it's not necessary) as so called ignoredNamespaces
which default to an Array of 3 Strings (['tns', 'targetNamespace', 'typedNamespace']
).
If this is not sufficient for your purpose you can easily add more namespace prefixes to this Array, or override it in its entirety by passing an ignoredNamespaces
object within the options
you pass in soap.createClient()
method.
A simple ignoredNamespaces
object, which only adds certain namespaces could look like this:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace']
}
}
This would extend the ignoredNamespaces
of the WSDL
processor to ['tns', 'targetNamespace', 'typedNamespace', 'namespaceToIgnore', 'someOtherNamespace']
.
If you want to override the default ignored namespaces you would simply pass the following ignoredNamespaces
object within the options
:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
override: true
}
}
This would override the default ignoredNamespaces
of the WSDL
processor to ['namespaceToIgnore', 'someOtherNamespace']
. (This shouldn't be necessary, anyways).
If you want to override the default ignored namespaces you would simply pass the following ignoredNamespaces
object within the options
:
var options = {
ignoredNamespaces: {
namespaces: ['namespaceToIgnore', 'someOtherNamespace'],
override: true
}
}
This would override the default ignoredNamespaces
of the WSDL
processor to ['namespaceToIgnore', 'someOtherNamespace']
. (This shouldn't be necessary, anyways).
Handling "ignoreBaseNameSpaces" attribute
If an Element in a schema
definition depends has a basenamespace defined but the request does not need that value, for example you have a "sentJob" with basenamespace "v20" but the request need only:
By default the attribute is set to true. An example to use:
A simple ignoredNamespaces
object, which only adds certain namespaces could look like this:
var options = {
ignoredNamespaces: true
}
soap-stub
Unit testing services that use soap clients can be very cumbersome. In order to get around this you can use soap-stub
in conjunction with sinon
to stub soap with your clients.
Example
// test-initialization-script.js
var sinon = require('sinon');
var soapStub = require('soap/soap-stub');
var urlMyApplicationWillUseWithCreateClient = 'http://path-to-my-wsdl';
var clientStub = {
SomeOperation: sinon.stub()
};
clientStub.SomeOperation.respondWithError = soapStub.createErroringStub({..error json...});
clientStub.SomeOperation.respondWithSuccess = soapStub.createRespondingStub({..success json...});
soapStub.registerClient('my client alias', urlMyApplicationWillUseWithCreateClient, clientStub);
// test.js
var soapStub = require('soap/soap-stub');
describe('myService', function() {
var clientStub;
var myService;
beforeEach(function() {
clientStub = soapStub.getStub('my client alias');
soapStub.reset();
myService.init(clientStub);
});
describe('failures', function() {
beforeEach(function() {
clientStub.SomeOperation.respondWithError();
});
it('should handle error responses', function() {
myService.somethingThatCallsSomeOperation(function(err, response) {
// handle the error response.
});
});
});
});
Contributors
- Author: Vinay Pulim
- Maintainers:
- Joe Spencer
- Heinz Romirer
- All Contributors