This is the first time me playing with Nginx & njs.
I am trying to find a way to get the value from the JSON request and pass it as a new header to the upstream.
I have the following function:
function extract (r) {
var json = JSON.parse(r.requestText);
var sessionid = json["sessionId"];
return sessionid;
}
And then:
js_set $sessionid http.extract;
I cannot assign the result of my function to the $sessionid
variable which then I will use to pass to the upstream server:
proxy_set_header Cookie "mycookie=$sessionid";
When I send the curl
command, the /var/log/nginx/error.log
gives me:
2024/11/28 01:10:20 [error] 64724#64724: *455 js exception: SyntaxError: Unexpected token at position 0
at JSON.parse (native)
at extract_sessionid (/etc/nginx/njs/http.js:3)
The r.requestText
is a JSON:
{ "sessionId":"F105" }
The value "F105" would be used to proxy add header.
Any idea?
Thank you.
2
Answers
From the documentation for
requestText
/requestBuffer
:As being noted, the
requestBuffer
/requestText
properties are available only in thejs_content
directive. Still, there is no reason to give up 🙂 Here are two methods that should help you achieve the result you’re looking for.Analyze the
requestText
property using thejs_content
location content handler and then jump to another location for further request processing:nginx.conf
extract_json_field.js
Use the
mirror
directive to populate$request_body
built-in nginx variable during thePREACCESS
request processing phase. This allows you to user.variables.request_body
in place of therequestText
property (inspired by this example):nginx.conf
extract_json_field.js
If you’d like njs, I can recommend two excellent resources: