I'm not at all sure whether my current method of calculating the content-length is correct. What are the implications of using string.length() to calculate the content-length. Does setting the charset to utf-8 even mean anything when using node.js?
payload = JSON.stringify( payload ); response.header( 'content-type', application/json; charset=utf-8 ); response.header( 'content-length', payload.length ); response.end( payload );
As bytes are represented with two hexadecimal digits, one can divide the number of digits by two to obtain the content length (There are 12 hexadecimal digits in "48656c6c6f21" which equates to six bytes, as indicated in the header "Content-Length: 6" sent from the server).
Content-Type in the response is the header we can set to inform how client would interpret the data from the server. For example, if you are sending down an HTML file to the client, you should set the Content-Type to text/html, which you can with the following code: response. setHeader("Content-Type", "text/html");
you should use JSON. stringify() to get the complete string then apply length attribute to get length. var data = { "Id": 1, "Value": 10, "UId" : "ab400" } var Length = JSON. stringify(data).
The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings.
Content-Length header must be the count of octets in the response body. payload.length
refers to string length in characters. Some UTF-8 characters contain multiple bytes. The better way would be to use Buffer.byteLength(string, [encoding])
from http://nodejs.org/api/buffer.html. It's a class method so you do not have to create any Buffer instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With