我正在使用环回连接器 REST (1.9.0) 并有一个返回 XML 的远程方法:
Foo.remoteMethod
(
"getXml",
{
accepts: [
{arg: 'id', type: 'string', required: true }
],
http: {path: '/:id/content', "verb": 'get'},
returns: {"type": "string", root:true},
rest: {"after": setContentType("text/xml") }
}
)
响应始终返回转义的 JSON 字符串:
"<foo xmlns=\"bar\"/>"
而不是
<foo xmlns="bar"/>
请注意,响应的内容类型确实设置为 text/xml。
如果我将 Accept: header 设置为“text/xml”,我总是会得到“Not Acceptable”作为响应。
如果我设置
"rest": {
"normalizeHttpPath": false,
"xml": true
}
在 config.json 中,我收到 500 错误:
SyntaxError: Unexpected token <
我认为“xml: true”属性只是导致响应解析器尝试将 JSON 转换为 XML。
如何让 Loopback 在不解析响应的情况下返回 XML?问题是我将返回类型设置为“string”吗?如果是这样,Loopback 会识别为 XML 的类型是什么?
最佳答案
您需要在响应对象中设置 toXML(稍后会详细介绍)。首先,将返回类型设置为“object”,如下所示:
Foo.remoteMethod
(
"getXml",
{
accepts: [
{arg: 'id', type: 'string', required: true }
],
http: {path: '/:id/content', "verb": 'get'},
returns: {"type": "object", root:true},
rest: {"after": setContentType("text/xml") }
}
)
接下来,您需要返回一个 JSON 对象,其中 toXML 作为唯一属性。 toXML 应该是一个返回 XML 字符串表示形式的函数。如果将 Accept header 设置为“text/xml”,则响应应该是 XML。见下文:
Foo.getXml = function(cb) {
cb(null, {
toXML: function() {
return '<something></something>';
}
});
};
您仍然需要在 config.json 中启用 XML,因为默认情况下它是禁用的:
"remoting": {
"rest": {
"normalizeHttpPath": false,
"xml": true
}
}
参见https://github.com/strongloop/strong-remoting/blob/4b74a612d3c969d15e3dcc4a6d978aa0514cd9e6/lib/http-context.js#L393有关其幕后工作原理的更多信息。
关于node.js - 从 Loopback 远程方法返回 XML 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31171438/