简体   繁体   中英

Multiple content type support for nodejs XML <-> JSON

I want to support both XML and JSON Content-Type for all the Rest API request to my server. Any thoughts on it?

I am thinking of adding middleware to check for the request's Content-Type / Accept and if its XML convert it into JSON and pass it to routes, and make sure that those responses are converted back in to XML before sending.

So my question is:

  • What is the optimal way of doing it?
  • Are there any exisiting libraries that does this?

I dont want to add addtional logic in each of the end points nor create new end points for it. Theres got to be a better way of doing this.

PS:I am using express.

EDIT: Requirements changed and I am not doing only one way translation (json to xm) using: [this] ( http://goessner.net/download/prj/jsonxml/ )

Use the Accept header to determine whether the client prefers JSON or XML as opposed to a query parameter. The semantics are the Accept header means "I would prefer to receive the following MIME types" and is only used on requests. The Content-Type header means "this message body is formatted in this MIME type" and can be used on responses and requests (when their is a message body). I would use this pattern:

  • During most of your route handlers, assemble the canonical response data representation as res.body . This should just be plain javascript object data. Call next() when done.
  • Add a middleware after the router that looks for an unsent response with res.body set, then based on the Accept header, formats res.body as XML or just does res.send(res.body) if the client wants JSON. You may be able to use the res.headerSent boolean to test whether the response is sent, or just make sure that res.body gets unset when sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM