Challenge : Content Type JSON not understood when Raw JSON is sent in POST method

This is really tricky and we spent lot of time to resolve it. We tried almost all the approaches suggested.
In some cases the external REST servers may not give issues and can trust the header tag for content type.
Our problem was that the REST service did not respond the content and did not work solely with Content type JSON header.

Problem statement :

  • Need to pass a raw JSON object like "username" , "password" to an external REST service without using the module like node curl ( we wanted to use standard node module like "http")
  • Server not able to understand the content type JSON and does not return correct response. Returns text/html.

Solution that comes to mind is pretty simple : e.g. To send a JSON "data" as raw data 

  • Set the header in request with "Content-Type : application/json"
  • And pass the object either in "json: {your json data} " or "data : {your json data}" and most recommended or trusted method , that we also used  is send the raw data as "request.write (json.stringify(data)) " 
  • You might find some other approaches as well..

What problem we faced 

  • We set the header to Json content type. 
  • We passed the raw data in request.write.
  • Despite of setting the things correctly, the response we received from server was in text/html.
  • We did not receive JSON.

Well after lot of research and hit and trial we thought of something about the behavior of node.

Reason for this behavior
Before the server received or waited for our Raw data in request.write, it returned us text/html (the server was not waiting for write on request for the raw data)

So what was the solution?

  • We used another header to tell server ( that we are sending some bytes of data ) and then to decide the communication data type or content type correctly and precisely
  • So in headers we used 'Content-Length' : Buffer.byteLength(data)
  • Sample code for you to use and understand this situation and resolve it is as below.




Hope you liked it


Comments