On this page
Module ngx_http_js_module
ngx_http_js_module
模块用于以njs(JavaScript 语言的一个子集)实现位置和变量处理程序。
here提供了下载和安装说明。
Example Configuration
该示例自0.4.0开始生效。
http {
js_import http.js;
js_set $foo http.foo;
js_set $summary http.summary;
server {
listen 8000;
location / {
add_header X-Foo $foo;
js_content http.baz;
}
location = /summary {
return 200 $summary;
}
location = /hello {
js_content http.hello;
}
}
}
http.js
文件:
function foo(r) {
r.log("hello from foo() handler");
return "foo";
}
function summary(r) {
var a, s, h;
s = "JS summary\n\n";
s += "Method: " + r.method + "\n";
s += "HTTP version: " + r.httpVersion + "\n";
s += "Host: " + r.headersIn.host + "\n";
s += "Remote Address: " + r.remoteAddress + "\n";
s += "URI: " + r.uri + "\n";
s += "Headers:\n";
for (h in r.headersIn) {
s += " header '" + h + "' is '" + r.headersIn[h] + "'\n";
}
s += "Args:\n";
for (a in r.args) {
s += " arg '" + a + "' is '" + r.args[a] + "'\n";
}
return s;
}
function baz(r) {
r.status = 200;
r.headersOut.foo = 1234;
r.headersOut['Content-Type'] = "text/plain; charset=utf-8";
r.headersOut['Content-Length'] = 15;
r.sendHeader();
r.send("nginx");
r.send("java");
r.send("script");
r.finish();
}
function hello(r) {
r.return(200, "Hello world!");
}
export default {foo, summary, baz, hello};
Directives
Syntax: | js_content function | module.function; |
Default: | — |
Context: | location , limit_except |
将 njs 函数设置为位置内容处理程序。由于0.4.0,因此可以引用模块功能。
Syntax: | js_import module.js | export_name from module.js; |
Default: | — |
Context: | http |
该指令出现在版本 0.4.0 中。
导入在 njs 中实现位置和变量处理程序的模块。 export_name
用作访问模块功能的名称空间。如果未指定export_name
,则模块名称将用作命名空间。
js_import http.js;
在这里,模块名称http
在访问导出时用作命名空间。如果导入的模块包含foo()
,则使用http.foo
来引用它。
可以指定多个js_import
指令。
Syntax: | js_include file; |
Default: | — |
Context: | http |
指定一个在 njs 中实现位置和变量处理程序的文件:
nginx.conf:
js_include http.js;
location /version {
js_content version;
}
http.js:
function version(r) {
r.return(200, njs.version);
}
自0.4.0以来,该指令已弃用,而应改用js_import指令。
Syntax: | js_path path; |
Default: | — |
Context: | http |
该指令出现在版本 0.3.0 中。
为 njs 模块设置附加路径。
Syntax: | js_set $variable function | module.function; |
Default: | — |
Context: | http |
为指定变量设置 njs 函数。由于0.4.0,因此可以引用模块功能。
Request Argument
每个 HTTP njs 处理程序都接收一个参数,即请求object。