Can't get response header values

2,872 views
Skip to first unread message

q2dg2b

unread,
Jan 26, 2015, 6:24:31 PM1/26/15
to expre...@googlegroups.com
Hello.
My code is so simple...:

var express = require("express")
var app = express()
app.get("/", function (req, res) {
    var mydate=res.get("date")  <--- http://expressjs.com/api.html#res.get
    console.log(mydate)
    res.end()
})
app.listen(4000)


...but when I write http://127.0.0.1:4000 in my browser I get "undefined" on console.

I've also checked if "Date" header is actually sent by server executing curl -i http://127.0.0.1:4000, and it is.

Thanks a lot for your help

Jason Crawford

unread,
Jan 26, 2015, 11:51:11 PM1/26/15
to expre...@googlegroups.com
Maybe the header isn't set at that point? There are some headers that are set by middleware only after you produce a response, or at least begin writing the first response headers. What if you try after the res.end()?

-Jason

--
You received this message because you are subscribed to the Google Groups "Express" group.
To unsubscribe from this group and stop receiving emails from it, send an email to express-js+...@googlegroups.com.
To post to this group, send email to expre...@googlegroups.com.
Visit this group at http://groups.google.com/group/express-js.
For more options, visit https://groups.google.com/d/optout.

q2dg2b

unread,
Jan 27, 2015, 5:11:59 AM1/27/15
to expre...@googlegroups.com
Thanks a lot for your answer: it seems very logical, but it doesn't work neither. This code...:

var express = require("express")
var app = express()
app.get("/", function (req, res) {
    res.end()
    var mydate=res.get("date")
    console.log(mydate)
})
app.listen(4000)


...gives the same result: "undefined"

q2dg2b .

unread,
Jan 27, 2015, 7:52:10 AM1/27/15
to Jérémy Lal, expre...@googlegroups.com
Oh, this has a lot of sense, too! But doesn't work neither (!!?) This code...

var express = require("express")
var of = require("on-finished")

var app = express()
app.get("/", function (req, res) {
    of(res, function (err) {

        var mydate=res.get("date") 
        console.log(mydate)
        })
        res.end()
})
app.listen(4000)

...and this code...

var express = require("express")
var of = require("on-finished")

var app = express()
app.get("/", function (req, res) {
    res.end()
    of(res, function (err) {

        var mydate=res.get("date") 
        console.log(mydate)
        })
})
app.listen(4000)


...gives the same result: "undefined" (!!?)

You gave me an idea, so I've also tried:

var express = require("express")
var of = require("on-finished")

var app = express()
app.get("/", function (req, res) {
    res.on("finish", function (err) {

        var mydate=res.get("date") 
        console.log(mydate)
        })
    res.end()
})
app.listen(4000)


....but with the same luck.

It's really really strange.
I'm using Express 4.11 (Node 0.11.14, Fedora 21 64 bits).
Thanks a lot for you answers!!!


2015-01-27 12:59 GMT+01:00 Jérémy Lal <kap...@melix.org>:
Tip: use https://github.com/jshttp/on-finished
npm install on-finished


Le mardi 27 janvier 2015 à 02:11 -0800, q2dg2b a écrit :
> Thanks a lot for your answer: it seems very logical, but it doesn't work
> neither. This code...:
>
>
>
>
>
> *var express = require("express")var app = express()app.get("/", function
> (req, res) {     res.end() *
>
>
> *    var mydate=res.get("date")     console.log(mydate) })app.listen(4000)*

q2dg2b .

unread,
Jan 27, 2015, 10:15:41 AM1/27/15
to Jérémy Lal, expre...@googlegroups.com
Ok! Thanks! Maybe we've discovered a bug!

2015-01-27 14:49 GMT+01:00 Jérémy Lal <kap...@melix.org>:
True ! I also tried res.getHeader() in case express was doing something
off with res.get(). Those headers might be set by node itself.
I'd check the source of http server.


Le mardi 27 janvier 2015 à 13:51 +0100, q2dg2b . a écrit :
> Oh, this has a lot of sense, too! But doesn't work neither (!!?) This
> code...
>
> var express = require("express")
> var of = require("on-finished")
> var app = express()
> app.get("/", function (req, res) {
>     of(res, function (err) {
>         var mydate=res.get("date")
>         console.log(mydate)
>         })
>         res.end()
> })
> app.listen(4000)
>
> ...and this code...
>
>
>
>
>
>
>
>
>
>
>
> *var express = require("express")var of = require("on-finished")var app =
> express()app.get("/", function (req, res) {    res.end()    of(res,

> function (err) {        var mydate=res.get("date")
> console.log(mydate)        })})app.listen(4000)*

>
> ...gives the same result: "undefined" (!!?)
>
> You gave me an idea, so I've also tried:
>
>
>
>
>
>
>
>
>
>
>
> *var express = require("express")var of = require("on-finished")var app =
> express()app.get("/", function (req, res) {    res.on("finish", function

> (err) {        var mydate=res.get("date")
> console.log(mydate)        })    res.end()})app.listen(4000)*

greelgorke

unread,
Jan 27, 2015, 10:32:21 AM1/27/15
to expre...@googlegroups.com
try to print the res.headers object to the log and see if your header is there. also you can check the res.headersSent flag. if its not sent, the headers may not be set yet.

q2dg2b .

unread,
Jan 27, 2015, 10:52:08 AM1/27/15
to expre...@googlegroups.com
Well, I´ve run this code:

var express = require("express")
var app = express()
app.get("/", function (req, res) {
    console.log("Before END")
    console.log("'res.headersSent' value:" ,res.headersSent)
    console.log("'res.headers' object:" ,res.headers)
    var mydate=res.get("date")  //Doing var mydate=res.getHeader("date") is the same
    console.log(mydate)
    res.end()
    console.log("After END")
    console.log("'res.headersSent' value:" ,res.headersSent)
    console.log("'res.headers' object:" ,res.headers)
})
app.listen(4000)


The output is:

Before END
'res.headersSent' value: false
'res.headers' object: undefined
undefined
After END
'res.headersSent' value: true
'res.headers' object: undefined



Surprised by las line ("'res.headers' object undefined") I've run a very similar but diferent code:

var express = require("express")
var app = express()
app.get("/", function (req, res) {
    console.log("Before END")
    console.log("'res' object:" ,res)
    var mydate=res.get("date")  //Doing var mydate=res.getHeader("date") is the same
    console.log(mydate)
        res.end()
    console.log("After END")
    console.log("'res' object" ,res)
})
app.listen(4000)


And the output is:

Before END
'res' object: { domain: null,
  _events: { prefinish: [Function: resOnFinish] },
  _maxListeners: undefined,
  output: [],
  outputEncodings: [],
  outputCallbacks: [],
  writable: true,
  _last: false,
  chunkedEncoding: false,
  shouldKeepAlive: true,
  useChunkedEncodingByDefault: true,
  sendDate: true,
  _removedHeader: {},
  _hasBody: true,
  _trailer: '',
  finished: false,
  _hangupClose: false,
  socket:
   { _connecting: false,
     _hadError: false,
     _handle:
      { fd: 12,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _host: null,
     _readableState:
      { objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: false },
     readable: true,
     domain: null,
     _events:
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function: socketOnError],
        close: [Object],
        data: [Function: socketOnData] },
     _maxListeners: undefined,
     _writableState:
      { objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     bytesRead: 319,
     _bytesDispatched: 0,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      { domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _connections: 1,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:null:4000' },
     _idleTimeout: 120000,
     _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idleStart: 2042255,
     parser:
      { '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        _headers: [],
        _url: '',
        socket: [Circular],
        incoming: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] },
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage: [Circular] },
  connection:
   { _connecting: false,
     _hadError: false,
     _handle:
      { fd: 12,
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _host: null,
     _readableState:
      { objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: false },
     readable: true,
     domain: null,
     _events:
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function: socketOnError],
        close: [Object],
        data: [Function: socketOnData] },
     _maxListeners: undefined,
     _writableState:
      { objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     destroyed: false,
     bytesRead: 319,
     _bytesDispatched: 0,
     _pendingData: null,
     _pendingEncoding: '',
     server:
      { domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _connections: 1,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:null:4000' },
     _idleTimeout: 120000,
     _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
     _idleStart: 2042255,
     parser:
      { '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        _headers: [],
        _url: '',
        socket: [Circular],
        incoming: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncoming] },
     _paused: false,
     read: [Function],
     _consuming: true,
     _httpMessage: [Circular] },
  _headers: { 'x-powered-by': 'Express' },
  _headerNames: { 'x-powered-by': 'X-Powered-By' },
  req:
   { _readableState:
      { objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: null,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: {},
     _maxListeners: undefined,
     socket:
      { _connecting: false,
        _hadError: false,
        _handle: [Object],
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 319,
        _bytesDispatched: 0,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 2042255,
        parser: [Object],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] },
     connection:
      { _connecting: false,
        _hadError: false,
        _handle: [Object],
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 319,
        _bytesDispatched: 0,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 2042255,
        parser: [Object],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] },
     httpVersionMajor: 1,
     httpVersionMinor: 1,
     httpVersion: '1.1',
     complete: false,
     headers:
      { host: '127.0.0.1:4000',
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0',
        accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'accept-language': 'ca,en-us;q=0.7,en;q=0.3',
        'accept-encoding': 'gzip, deflate',
        connection: 'keep-alive',
        'cache-control': 'max-age=0' },
     rawHeaders:
      [ 'Host',
        '127.0.0.1:4000',
        'User-Agent',
        'Mozilla/5.0 (X11; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0',
        'Accept',
        'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language',
        'ca,en-us;q=0.7,en;q=0.3',
        'Accept-Encoding',
        'gzip, deflate',
        'Connection',
        'keep-alive',
        'Cache-Control',
        'max-age=0' ],
     trailers: {},
     rawTrailers: [],
     _pendings: [],
     _pendingIndex: 0,
     upgrade: false,
     url: '/',
     method: 'GET',
     statusCode: null,
     statusMessage: null,
     client:
      { _connecting: false,
        _hadError: false,
        _handle: [Object],
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 319,
        _bytesDispatched: 0,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 2042255,
        parser: [Object],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: [Circular] },
     _consuming: false,
     _dumped: false,
     next: [Function: next],
     baseUrl: '',
     originalUrl: '/',
     _parsedUrl:
      { protocol: null,
        slashes: null,
        auth: null,
        host: null,
        port: null,
        hostname: null,
        hash: null,
        search: null,
        query: null,
        pathname: '/',
        path: '/',
        href: '/',
        _raw: '/' },
     params: {},
     query: {},
     res: [Circular],
     route: { path: '/', stack: [Object], methods: [Object] } },
  locals: {} }
undefined
After END
'res' object { domain: null,
  _events: { prefinish: [Function: resOnFinish] },
  _maxListeners: undefined,
  output: [],
  outputEncodings: [],
  outputCallbacks: [],
  writable: true,
  _last: false,
  chunkedEncoding: true,
  shouldKeepAlive: true,
  useChunkedEncodingByDefault: true,
  sendDate: true,
  _removedHeader: {},
  _hasBody: true,
  _trailer: '',
  finished: true,
  _hangupClose: false,
  socket: null,
  connection: null,
  _headers: { 'x-powered-by': 'Express' },
  _headerNames: { 'x-powered-by': 'X-Powered-By' },
  req:
   { _readableState:
      { objectMode: false,
        highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: true },
     readable: true,
     domain: null,
     _events: {},
     _maxListeners: undefined,
     socket:
      { _connecting: false,
        _hadError: false,
        _handle: [Object],
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 319,
        _bytesDispatched: 136,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 2042291,
        parser: [Object],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: null },
     connection:
      { _connecting: false,
        _hadError: false,
        _handle: [Object],
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 319,
        _bytesDispatched: 136,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 2042291,
        parser: [Object],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: null },
     httpVersionMajor: 1,
     httpVersionMinor: 1,
     httpVersion: '1.1',
     complete: false,
     headers:
      { host: '127.0.0.1:4000',
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0',
        accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'accept-language': 'ca,en-us;q=0.7,en;q=0.3',
        'accept-encoding': 'gzip, deflate',
        connection: 'keep-alive',
        'cache-control': 'max-age=0' },
     rawHeaders:
      [ 'Host',
        '127.0.0.1:4000',
        'User-Agent',
        'Mozilla/5.0 (X11; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0',
        'Accept',
        'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language',
        'ca,en-us;q=0.7,en;q=0.3',
        'Accept-Encoding',
        'gzip, deflate',
        'Connection',
        'keep-alive',
        'Cache-Control',
        'max-age=0' ],
     trailers: {},
     rawTrailers: [],
     _pendings: [],
     _pendingIndex: 0,
     upgrade: false,
     url: '/',
     method: 'GET',
     statusCode: null,
     statusMessage: null,
     client:
      { _connecting: false,
        _hadError: false,
        _handle: [Object],
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        destroyed: false,
        bytesRead: 319,
        _bytesDispatched: 136,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 2042291,
        parser: [Object],
        _paused: false,
        read: [Function],
        _consuming: true,
        _httpMessage: null },
     _consuming: false,
     _dumped: true,
     next: [Function: next],
     baseUrl: '',
     originalUrl: '/',
     _parsedUrl:
      { protocol: null,
        slashes: null,
        auth: null,
        host: null,
        port: null,
        hostname: null,
        hash: null,
        search: null,
        query: null,
        pathname: '/',
        path: '/',
        href: '/',
        _raw: '/' },
     params: {},
     query: {},
     res: [Circular],
     route: { path: '/', stack: [Object], methods: [Object] } },
  locals: {},
  statusMessage: 'OK',
  statusCode: 200,
  _header: 'HTTP/1.1 200 OK\r\nX-Powered-By: Express\r\nDate: Tue, 27 Jan 2015 15:48:37 GMT\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\n',
  _headerSent: true }

It appears a "res._headers" property, a "res._header" property and a "req.headers" object (inside res!?) but there aren't any "res.headers" object. Sorry but my knowledge doesnt' go more far away...
Thanks


--
You received this message because you are subscribed to a topic in the Google Groups "Express" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/express-js/hvJ9b1FidH4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to express-js+...@googlegroups.com.

greelgorke

unread,
Jan 29, 2015, 9:37:18 AM1/29/15
to expre...@googlegroups.com
ok.

the date header is set by the node.js core, not by express. You can only get this header out, if it's set and not sent yet. so your case, at the time you check it, it is not set yet. i tried to get it also, but wasn't able to.

so lets turn it around: why do you need this information? if it's important, then you could set the date header by yourself.


Am Dienstag, 27. Januar 2015 00:24:31 UTC+1 schrieb q2dg2b:

q2dg2b .

unread,
Jan 29, 2015, 2:05:51 PM1/29/15
to expre...@googlegroups.com
Well...the real core explanation is here: https://github.com/iojs/io.js/issues/653
Thanks a lot for your patience!!!

--
Reply all
Reply to author
Forward
0 new messages