Error: ERR_CONTENT_LENGTH_MISMATCH error: Content-length error: ERR_CONTENT_LENGTH_MISMATCH error: Content-length error: ERR_CONTENT_LENGTH_MISMATCH error: Content-length error: ERR_CONTENT_LENGTH_MISMATCH error: Content-length error: ERR_CONTENT_LENGTH_MISMATCH

Content-Length

Developer.mozilla.org/en-US/docs/…

Content-length Entity header indicates the size, in bytes, of the entity body to be sent to the receiver. An 8-bit byte identified in decimal notation.

Content received by the browser will be truncated if it is set to a content-Length smaller than the correct Content Length. The body and HTML tags have been truncated as follows:

If it is large, the browser will wait for more content to load and then throw ERR_CONTENT_LENGTH_MISMATCH.

res.setHeader('Content-Length', len + 200)
Copy the code

English, number length calculation

When setting content-Length on the server, you can set charset to UTF-8. When we calculate the length, in UTF-8 encoding, English and digits are encoded in one byte. The following pseudocode:

const INJECT_STR = fs.readFileSync('./inject', { encoding: 'utf-8' })
// On return
let len = INJECT_STR.length
len += res.getHeader('Content-Length')
res.setHeader('Content-Length', len)
Copy the code

There is no problem with this in general, but the premise is that there is no Chinese in inject file. If there is Chinese, there will be truncation.

Chinese length calculation

In UTF-8, most Chinese characters are 3 bytes, and the length of the string is 1, which causes the resulting length to be smaller than the actual length, resulting in truncation. The method of calculation can be calculated by the following method,

Refer to see stackoverflow.com/questions/5…

1. Blob size

var str = 'China'
new Blob([str]).size / / 6
Copy the code

2. charCodeAt

Stackoverflow.com/questions/5…

function byteLength(str) {
  // returns the byte length of an UTF-8 string
  var s = str.length;
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s+=2;
    if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
  }
  return s;
}
byteLength(str) / / 6
Copy the code

3. Buffer.byteLength

# node
> var str = 'China'
undefined
> Buffer.byteLength(str, 'utf8'6)Copy the code

conclusion

  1. If Chinese is not possible, try to use English.
  2. Use the method to calculate correctlyContent-Length.
  3. The node is used inBuffer.byteLengthorBlobCompute the length.