从Loopback Remote Method返回XML

dj_*_*_md 1 node.js express loopbackjs

我正在使用Loopback Connector 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") }         
      }
   )
Run Code Online (Sandbox Code Playgroud)

响应始终返回转义的JSON字符串:

"<foo xmlns=\"bar\"/>" 
Run Code Online (Sandbox Code Playgroud)

代替

<foo xmlns="bar"/>
Run Code Online (Sandbox Code Playgroud)

请注意,响应的内容类型设置为text/xml.

如果我将Accept:标题设置为"text/xml",我总是将"Not Acceptable"作为响应.

如果我订

"rest": {
  "normalizeHttpPath": false,
  "xml": true
}
Run Code Online (Sandbox Code Playgroud)

在config.json中,然后我得到500错误:

SyntaxError: Unexpected token <
Run Code Online (Sandbox Code Playgroud)

我认为"xml:true"属性只是导致响应解析器尝试将JSON转换为XML.

如何在不解析的情况下让Loopback返回响应中的XML?问题是我将返回类型设置为"string"?如果是这样,Loopback会识别为XML的类型是什么?

小智 5

您需要在响应对象中设置为XML(稍后会详细介绍).首先,将返回类型设置为'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") }         
  }
)
Run Code Online (Sandbox Code Playgroud)

接下来,您将需要返回一个带有toXML的JSON对象作为唯一属性.toXML应该是一个返回XML的字符串表示的函数.如果将Accept标头设置为"text/xml",则响应应为XML.见下文:

Foo.getXml = function(cb) {
  cb(null, {
    toXML: function() {
      return '<something></something>';
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

您仍然需要在config.json中启用XML,因为它默认情况下已禁用:

"remoting": {
  "rest": {
    "normalizeHttpPath": false,
    "xml": true
  }
}
Run Code Online (Sandbox Code Playgroud)

有关如何在幕后工作的更多信息,请参阅https://github.com/strongloop/strong-remoting/blob/4b74a612d3c969d15e3dcc4a6d978aa0514cd9e6/lib/http-context.js#L393.