I am trying to make a POST http.request in Node to an API where the body is JSON. I convert my object to a JSON string using JSON.stringify, however when I write the string to the request and look at my request it double escapes the data i.e. \ becomes \\\\.
jsonData = JSON.stringify(myObject)
// everything is a correct JSON string, with slashes escapped once
post_req.write(jsonData, 'binary')
post_req.end()
console.log post_req // the JSON string was actually sent double escapped
Any tips on how to stop Node automatically double escaping the JSON?
When I take my jsonData and curl or hurl.it it to the server everything works as expected.
Your data isn’t binary, it’s a string, so just omit the ‘binary’ parameter to
post_req.write(jsonData), and it will use utf8, which is what you want. Are you sure the double-escaping is really going over the wire and you aren’t being tricked by trying toconsole.logthe post_req object itself?