-1
 //req.headers = {
    {
      host: 'localhost:5000',
      connection: 'keep-alive',
      'content-length': '702',
      'cache-control': 'max-age=0',
      'upgrade-insecure-requests': '1', 
      '...'}

I'm using node.js I'm trying to extract the 'content-length' from the http req object. When I console.log(req.headers); I keep getting the following which doesn't allow me to directly access the data I need:

enter image description here

I need the data so I can check for the size of uploaded files. It looks like it should be an easy solution, but I'm stuck. I would appreciate any help thanks!

cahe1540
  • 47
  • 5
  • 3
    so , `req.data['content-length']` doesn't work? why are headers in req.data though? woudn't they be in `req.headers`? – Jaromanda X Oct 26 '20 at 23:34
  • 2
    `req.headers["content-length"]` – ibrahim mahrir Oct 26 '20 at 23:34
  • Are you looking for the request body? Are you aware that HTTP request are not necessarily sent in one message? They can be split in multiple messages and usually the header is sent alone without body and the body is sent in later messages. Therefor you can't read the body on the first event. You have to subscribe to `req.on('data', ...)` – Thomas Sablik Oct 26 '20 at 23:36
  • "But I'm stuck" does not help much. What are you getting instead and when? Any error messages? Can you provide some code in an MWE? – Joel Oct 26 '20 at 23:53
  • @Joel, If I type out console.log(req.headers.content-length). I get an undefined error. – cahe1540 Oct 27 '20 at 00:06
  • 2
    `console.log(req.headers['content-length'])` – Thomas Sablik Oct 27 '20 at 00:08
  • @all, omg... I could have sworn I tried that req.data['content-length']. What silly mistake. Thanks for the input. – cahe1540 Oct 27 '20 at 00:10
  • Everytime, your property is not just a string, you need to use the bracket syntax. So: `req.headers.property` works, `req.headers.property-with-dashes` does not, `req.headers['property-with-dashes']` would work again – Joel Oct 27 '20 at 00:10
  • Yes, thanks everyone. – cahe1540 Oct 27 '20 at 00:13

1 Answers1

1

HTTP requests are not necessarily sent in one message. They can be split in multiple messages and usually the headers are sent alone without body and the body is sent in later messages. Therefor you can't read the body on the first event. You have to subscribe to

req.on('data', (data) => {
    // ...
});

Usually you would do something like:

req.setEncoding('utf8');
let message = '';
req.on('data', (d) => {
    message += d;
});
const promise = new Promise(resolve => {
    req.on('end', () => {
        resolve(message);
    }
}
console.log(await promise);

If you are looking for the header 'content-length' you can access it with

req.headers['content-length']
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62