Njs: r.headersIn is undefined but r.headersIn['Authorization'] exists

Created on 9 Jul 2019  路  4Comments  路  Source: nginx/njs

Njs version: nginx-module-njs-1.17.1.0.3.3-1.el7.ngx.x86_64

typeof r.headersIn // undefined
typeof r.headersIn['Authorization'] // string

I cannot iterate over all headers because r.headersIn is always undefined. So Object.keys(r.headersIn) won't iterate over existing header keys.

answered question

Most helpful comment

@porunov

Please, see this #16. It is a longstanding issue. For performance reasons external objects are not the same as ordinary Js objects, instead they are thin wrappers around nginx structures. They support only a fixed set of operations, not everything that js objects support.

For example r.headersIn supports: https://github.com/nginx/njs/blob/master/nginx/ngx_http_js_module.c#L307

1) simple get by name r.headersIn['xxx'] or r.headersIn.xxx
2) iteration by for loop

var s, h;
s = "Headers:\n";
for (h in r.headersIn) {
    s += "  header '" + h + "' is '" + r.headersIn[h] + "'\n";
}

We are planning to add support for external objects for some often-used functions like Object.keys() or new Object() (DONE in 0.4.0)

All 4 comments

@porunov

Please, see this #16. It is a longstanding issue. For performance reasons external objects are not the same as ordinary Js objects, instead they are thin wrappers around nginx structures. They support only a fixed set of operations, not everything that js objects support.

For example r.headersIn supports: https://github.com/nginx/njs/blob/master/nginx/ngx_http_js_module.c#L307

1) simple get by name r.headersIn['xxx'] or r.headersIn.xxx
2) iteration by for loop

var s, h;
s = "Headers:\n";
for (h in r.headersIn) {
    s += "  header '" + h + "' is '" + r.headersIn[h] + "'\n";
}

We are planning to add support for external objects for some often-used functions like Object.keys() or new Object() (DONE in 0.4.0)

@xeioex Thank you very much for sharing a workaround for headers iteration. It what I was looking for

FWIW, i created a small function that let's me debug the njs objects like headersIn and headersOut, would really love to JSON.stringify and debug them, but this is what we have.

function _debug(njsObj) {
  // nginx internal objects don't support Object.keys/entries/values
  // we iterate and create js object instead for debugging
  // see: https://github.com/nginx/njs/issues/192
  var obj = {};
  for (var prop in njsObj) {
    obj[prop] = njsObj[prop];
  }
  return JSON.stringify(obj, null, '  ');
}

@nojvek
@porunov

Since https://github.com/nginx/njs/commit/0fa4360a5965b66a9055d3b0cd1170faa758365e (0.3.8), JSON.stringify() is supported.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

porunov picture porunov  路  3Comments

rainerhenrichsen picture rainerhenrichsen  路  5Comments

an0ma1ia picture an0ma1ia  路  4Comments

drsm picture drsm  路  4Comments

drsm picture drsm  路  5Comments