view xml/en/docs/njs/njs_api.xml @ 2178:cb431c861670

Added njs examples.
author Yaroslav Zhuravlev <yar@nginx.com>
date Tue, 05 Jun 2018 18:23:50 +0300
parents 79297494d291
children 7865ca0da0ab
line wrap: on
line source

<?xml version="1.0"?>

<!--
  Copyright (C) Nginx, Inc.
  -->

<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd">

<article name="njs API"
        link="/en/docs/njs/njs_api.html"
        lang="en"
        rev="2">

<section id="summary">

<para>
<link doc="../njs_about.xml">njs</link> provides objects, methods and properties
for extending nginx functionality.
</para>

</section>


<section id="core" name="Core">


<section id="core_json" name="JSON">

<para>
The <literal>JSON</literal> object (ES 5.1) provides functions
to convert njs values to and from JSON format.
<list type="tag">

<tag-name><literal>JSON.parse(<value>string</value>[,
<value>reviver</value>])</literal></tag-name>
<tag-desc>
Converts a <literal>string</literal> that represents JSON data
into an njs object (<literal>{...}</literal>) or
array (<literal>[...]</literal>).
The optional <literal>reviver</literal> parameter is a function (key, value)
that will be called for each (key,value) pair and can transform the value.
</tag-desc>

<tag-name><literal>JSON.stringify(<value>value</value>[,
<value>replacer</value>] [, <value>space</value>])</literal></tag-name>
<tag-desc>
Converts an njs object back to JSON.
The obligatory <literal>value</literal> parameter is generally a JSON
<literal>object</literal> or <literal>array</literal> that will be converted.
If the value has a <literal>toJSON()</literal> method,
it defines how the object will be serialized.
The optional <literal>replacer</literal> parameter is
a <literal>function</literal> or <literal>array</literal>
that transforms results.
The optional <literal>space</literal> parameter is
a <literal>string</literal> or <literal>number</literal>.
If it is a <literal>number</literal>,
it indicates the number of white spaces placed before a result
(no more than 10).
If it is a <literal>string</literal>,
it is used as a white space (or first 10 characters of it).
If omitted or is <literal>null</literal>, no white space is used.
</tag-desc>
</list>
</para>

<para>
<example>
>> var json = JSON.parse('{"a":1, "b":true}')
>> json.a
1

>> JSON.stringify(json)
{"a":1,"b":true}

>> JSON.stringify(json, undefined, 1)
{
"a": 1,
"b": true
}

>> JSON.stringify({ x: [10, undefined, function(){}] })
{"x":[10,null,null]}

>> JSON.stringify({"a":1, "toJSON": function() {return "xxx"}})
"xxx"

# Example with function replacer

>> function replacer(key, value) {return (typeof value === 'string') ? undefined : value}
>>JSON.stringify({a:1, b:"b", c:true}, replacer)
{"a":1,"c":true}
</example>
</para>

</section>


<section id="crypto" name="Crypto">

<para>
The Crypto module provides cryptographic functionality support.
The Crypto module object is returned by <literal>require('crypto')</literal>.
</para>

<para>
<list type="tag">

<tag-name><literal>crypto.createHash(<value>algorithm</value>)</literal></tag-name>
<tag-desc>
Creates and returns a <link id="crypto_hash">Hash</link> object
that can be used to generate hash digests
using the given <value>algorithm</value>.
The algorighm can be
<literal>md5</literal>,
<literal>sha1</literal>, and
<literal>sha256</literal>.
</tag-desc>

<tag-name><literal>crypto.createHmac(<value>algorithm</value>,
<value>secret key</value>)</literal></tag-name>
<tag-desc>
Creates and returns an <link id="crypto_hmac">HMAC</link> object
that uses the given <value>algorithm</value> and <value>secret key</value>.
The algorighm can be
<literal>md5</literal>,
<literal>sha1</literal>, and
<literal>sha256</literal>.
</tag-desc>

</list>
</para>


<section id="crypto_hash" name="Hash">

<para>
<list type="tag">

<tag-name><literal>hash.update(<value>data</value>)</literal></tag-name>
<tag-desc>
Updates the hash content with the given <value>data</value>.
</tag-desc>

<tag-name><literal>hash.digest([<value>encoding</value>])</literal></tag-name>
<tag-desc>
Calculates the digest of all of the data passed using
<literal>hash.update()</literal>.
The encoding can be
<literal>hex</literal>,
<literal>base64</literal>, and
<literal>base64url</literal>.
If encoding is not provided, a byte string is returned.
</tag-desc>

</list>
</para>

<para>
<example>
>> var cr = require('crypto')
undefined

>> cr.createHash('sha1').update('A').update('B').digest('base64url')
BtlFlCqiamG-GMPiK_GbvKjdK10
</example>
</para>

</section>


<section id="crypto_hmac" name="HMAC">

<para>
<list type="tag">

<tag-name><literal>hmac.update(<value>data</value>)</literal></tag-name>
<tag-desc>
Updates the HMAC content with the given <value>data</value>.
</tag-desc>

<tag-name><literal>hmac.digest([<value>encoding</value>])</literal></tag-name>
<tag-desc>
Calculates the HMAC digest of all of the data passed using
<literal>hmac.update()</literal>.
The encoding can be
<literal>hex</literal>,
<literal>base64</literal>, and
<literal>base64url</literal>.
If encoding is not provided, a byte string is returned.
</tag-desc>
</list>
</para>

<para>
<example>
>> var cr = require('crypto')
undefined

>> cr.createHmac('sha1', 'secret.key').update('AB').digest('base64url')
Oglm93xn23_MkiaEq_e9u8zk374
</example>
</para>

</section>

</section>

</section>


<section id="http" name="HTTP">

<para>
The <literal>HTTP</literal> objects are available only in the
<link doc="../http/ngx_http_js_module.xml">ngx_http_js_module</link> module.
</para>


<section id="http_request" name="Request">

<para>
<list type="tag">

<tag-name><literal>req.uri</literal></tag-name>
<tag-desc>
current URI in a request, read-only
</tag-desc>

<tag-name><literal>req.method</literal></tag-name>
<tag-desc>
request method, read-only
</tag-desc>

<tag-name><literal>req.httpVersion</literal></tag-name>
<tag-desc>
HTTP version, read-only
</tag-desc>

<tag-name><literal>req.remoteAddress</literal></tag-name>
<tag-desc>
client address, read-only
</tag-desc>

<tag-name><literal>req.headers{}</literal></tag-name>
<tag-desc>
request headers object, read-only.
<para>
For example, the <literal>Header-Name</literal> header
can be accessed with the syntax <literal>headers['Header-Name']</literal>
or <literal>headers.Header_name</literal>
</para>
</tag-desc>

<tag-name><literal>req.args{}</literal></tag-name>
<tag-desc>
request arguments object, read-only
</tag-desc>

<tag-name><literal>request.variables{}</literal></tag-name>
<tag-desc>
nginx variables object, read-only
</tag-desc>

<tag-name><literal>req.response</literal></tag-name>
<tag-desc>
the <link id="http_response">response</link> object (0.2.0), read-only
</tag-desc>

<tag-name><literal>req.log(<value>string</value>)</literal></tag-name>
<tag-desc>
writes a <literal>string</literal> to the error log
on the <literal>info</literal> level of logging
</tag-desc>

<tag-name><literal>req.warn(<value>string</value>)</literal></tag-name>
<tag-desc>
writes a <literal>string</literal> to the error log
on the <literal>warning</literal> level of logging (0.2.0)
</tag-desc>

<tag-name><literal>req.error(<value>string</value>)</literal></tag-name>
<tag-desc>
writes a <literal>string</literal> to the error log
on the <literal>error</literal> level of logging (0.2.0)
</tag-desc>

<tag-name id="subrequest"><literal>req.subrequest(<value>uri</value>[,
<value>options</value>[, <value>callback</value>]])</literal></tag-name>
<tag-desc>
creates a subrequest with the given <literal>uri</literal> and
<literal>options</literal>, and installs
an optional completion <literal>callback</literal> (0.2.0).

<para>
If <literal>options</literal> is a string, then it
holds the subrequest arguments string.
Otherwise, <literal>options</literal> is expected to be
an object with the following keys:

<list type="tag">
<tag-name><literal>args</literal></tag-name>
<tag-desc>
arguments string
</tag-desc>

<tag-name><literal>body</literal></tag-name>
<tag-desc>
request body
</tag-desc>

<tag-name><literal>method</literal></tag-name>
<tag-desc>
HTTP method
</tag-desc>
</list>
</para>

<para>
The completion <literal>callback</literal>
receives a <link id="http_reply_object">reply</link> object.
</para>
</tag-desc>

</list>
</para>

</section>


<section id="http_response" name="Response">

<para>
<list type="tag">

<tag-name><literal>res.status</literal></tag-name>
<tag-desc>
response status, writable
</tag-desc>

<tag-name><literal>res.headers{}</literal></tag-name>
<tag-desc>
response headers object
</tag-desc>

<tag-name><literal>res.contentType</literal></tag-name>
<tag-desc>
the response <header>Content-Type</header> header field value, writable
</tag-desc>

<tag-name><literal>res.contentLength</literal></tag-name>
<tag-desc>
the response <header>Content-Length</header> header field value, writable
</tag-desc>

<tag-name><literal>res.sendHeader()</literal></tag-name>
<tag-desc>
sends the HTTP header to the client
</tag-desc>

<tag-name><literal>res.send(<value>string</value>)</literal></tag-name>
<tag-desc>
sends a part of the response body to the client
</tag-desc>

<tag-name><literal>res.finish()</literal></tag-name>
<tag-desc>
finishes sending a response to the client
</tag-desc>

<tag-name><literal>res.return(status[, string])</literal></tag-name>
<tag-desc>
sends
the entire response with the specified <literal>status</literal> to the client
(0.2.0)
<para>
It is possible to specify either a redirect URL
(for codes 301, 302, 303, 307, and 308)
or the response body text (for other codes) as the second argument
</para>
</tag-desc>

</list>
</para>

</section>


<section id="http_reply" name="Reply">

<para>
<list type="tag">

<tag-name><literal>reply.uri</literal></tag-name>
<tag-desc>
current URI in a reply, read-only
</tag-desc>

<tag-name><literal>reply.method</literal></tag-name>
<tag-desc>
reply method, read-only
</tag-desc>

<tag-name><literal>reply.status</literal></tag-name>
<tag-desc>
reply status, writable
</tag-desc>

<tag-name><literal>reply.contentType</literal></tag-name>
<tag-desc>
the response <header>Content-Type</header> header field value, writable
</tag-desc>

<tag-name><literal>reply.contentLength</literal></tag-name>
<tag-desc>
the response <header>Content-Length</header> header field value, writable
</tag-desc>

<tag-name><literal>reply.headers{}</literal></tag-name>
<tag-desc>
reply headers object, read-only
</tag-desc>

</list>
</para>

<para>
Additionally, the <literal>reply</literal> object has
the following properties:

<list type="tag">

<tag-name><literal>reply.body</literal></tag-name>
<tag-desc>
holds the subrequest response body
</tag-desc>

<tag-name><literal>reply.parent</literal></tag-name>
<tag-desc>
references the parent request object
</tag-desc>

</list>
</para>

</section>

</section>


<section id="stream" name="Stream">

<para>
The <literal>stream</literal> objects are available only in the
<link doc="../stream/ngx_stream_js_module.xml">ngx_stream_js_module</link>
module.
</para>


<section id="stream_session" name="Session">

<para>
<list type="tag">

<tag-name><literal>s.remoteAddress</literal></tag-name>
<tag-desc>
client address, read-only
</tag-desc>

<tag-name><literal>s.eof</literal></tag-name>
<tag-desc>
a boolean read-only property, true if the current buffer is the last buffer
</tag-desc>

<tag-name><literal>s.fromUpstream</literal></tag-name>
<tag-desc>
a boolean read-only property,
true if the current buffer is from the upstream server to the client
</tag-desc>

<tag-name><literal>s.buffer</literal></tag-name>
<tag-desc>
the current buffer, writable
</tag-desc>

<tag-name><literal>s.variables{}</literal></tag-name>
<tag-desc>
nginx variables object, read-only
</tag-desc>

<tag-name><literal>s.OK</literal></tag-name>
<tag-desc>
the <literal>OK</literal> return code
</tag-desc>

<tag-name><literal>s.DECLINED</literal></tag-name>
<tag-desc>
the <literal>DECLINED</literal> return code
</tag-desc>

<tag-name><literal>s.AGAIN</literal></tag-name>
<tag-desc>
the <literal>AGAIN</literal> return code
</tag-desc>

<tag-name><literal>s.ERROR</literal></tag-name>
<tag-desc>
the <literal>ERROR</literal> return code
</tag-desc>

<tag-name><literal>s.ABORT</literal></tag-name>
<tag-desc>
the <literal>ABORT</literal> return code
</tag-desc>

<tag-name><literal>s.log(<value>string</value>)</literal></tag-name>
<tag-desc>
writes a sent <value>string</value> to the error log
on the <literal>info</literal> level of logging
</tag-desc>

<tag-name><literal>s.warn(<value>string</value>)</literal></tag-name>
<tag-desc>
writes a sent <literal>string</literal> to the error log
on the <literal>warning</literal> level of logging (0.2.0)
</tag-desc>

<tag-name><literal>s.error(<value>string</value>)</literal></tag-name>
<tag-desc>
writes a sent <literal>string</literal> to the error log
on the <literal>error</literal> level of logging (0.2.0)
</tag-desc>

</list>
</para>

</section>

</section>


<section id="example" name="Examples">


<section id="example_urldecode" name="URL Decoding">

<para>
<example>
js_include urldecode.js;

js_set $decoded_foo decoded_foo;
</example>
</para>

<para>
The <path>urldecode.js</path> file:
<example>
function decoded_foo(req, res) {
    return decodeURIComponent(req.args.foo);
}
</example>
</para>

</section>


<section id="example_urlencode" name="URL Encoding">

<para>
<example>
js_include urlencode.js;

js_set $encoded_foo encoded_foo;
...

location / {
    proxy_pass http://example.com?foo=$encoded_foo;
}
</example>
</para>

<para>
The <path>urlencode.js</path> file:
<example>
function encoded_foo(req, res) {
    return encodeURIComponent('foo &amp; bar?');
}
</example>
</para>

</section>


<section id="example_fast_response" name="Returning Fastest Response from Proxy">

<para>
<example>
js_include fastresponse.js;

location /start {
    js_content content;
}

location /foo {
    proxy_pass http://backend1;
}

location /bar {
    proxy_pass http://backend2;
}
</example>
</para>

<para>
The <path>fastresponse.js</path> file:
<example>
function content(req, res) {
    var n = 0;

    function done(reply) {
        if (n++ == 0) {
            res.return(reply.status, reply.body);
        }
    }

    req.subrequest('/foo', req.variables.args, done);
    req.subrequest('/bar', req.variables.args, done);
}
</example>
</para>

</section>


<section id="example_jwt" name="Creating HS JWT">

<para>
<example>
js_include hs_jwt.js;

js_set $jwt jwt;
</example>
</para>

<para>
The <path>hs_jwt.js</path> file:
<example>
function create_hs256_jwt(claims, key, valid) {
    var header = { "typ" : "JWT", "alg" : "HS256", "exp" : Date.now() + valid };

    var s = JSON.stringify(header).toBytes().toString('base64url') + '.'
            + JSON.stringify(claims).toBytes().toString('base64url');

    var h = require('crypto').createHmac('sha256', key);

    return s + '.' + h.update(s).digest().toString('base64url');
}

function jwt(req, res) {
    var claims = {
        "iss" : "nginx",
        "sub" : "alice",
        "foo" : 123,
        "bar" : "qq",
        "zyx" : false
    };

    return create_hs256_jwt(claims, 'foo', 600);
}
</example>
</para>

</section>


<section id="example_subrequest" name="Accessing API from a Subrequest">

<para>
<example>
js_include subrequest.js;

keyval_zone zone=foo:10m;
...

location /keyval {
    js_content set_keyval;
}

location /version {
    js_content version;
}

location /api {
    api write=on;
}
</example>
</para>

<para>
The <path>subrequest.js</path> file:
<example>
function set_keyval(req, res) {
    req.subrequest('/api/3/http/keyvals/foo',
        { method: 'POST',
          body: JSON.stringify({ foo: 789, bar: "ss dd 00" })},

        function(reply) {
            if (reply.status >= 300) {
                res.return(reply.status, reply.body);
                return;
            }
            res.return(500);
        });
}
function version(req, res) {
    req.subrequest('/api/3/nginx', { method: 'GET' }, function(reply) {
        if (reply.status != 200) {
            res.return(reply.status);
            return;
        }

        var json = JSON.parse(reply.body);
        res.return(200, json.version);
    });
}
</example>
</para>

</section>


<section id="example_secure_link" name="Creating secure_link Hash">

<para>
<example>
js_include hash.js;

js_set $new_foo create_secure_link;
...

location / {
    secure_link $cookie_foo;
    secure_link_md5 "$uri mykey";
    ...
}

location @login {
    add_header Set-Cookie "foo=$new_foo; Max-Age=60";
    return 302 /;
}
</example>
</para>

<para>
The <path>hash.js</path> file:
<example>
function create_secure_link(req, res) {
    return require('crypto').createHash('md5')
                            .update(req.uri).update(" mykey")
                            .digest('base64url');
}
</example>
</para>

</section>

</section>

</article>