Handling Input
Achieve prepares common client input as session.params. Your servlet can read those values without adding a body-parser package.
GET query parameters
For GET requests, Achieve parses the query string into session.params. This form sends a value named name:
<form action="/servlets/greet.jss" method="get">
<label>Name <input name="name"></label>
<button type="submit">Say hello</button>
</form>
The servlet reads the value directly:
exports.servlet = function(session) {
let name = session.params.name || "visitor";
return "Hello, " + name + "!";
};
A request such as /servlets/greet.jss?name=Ada therefore returns Hello, Ada!.
POST form data
A normal HTML POST form sends application/x-www-form-urlencoded data. Achieve buffers and parses that body into session.params before invoking the servlet:
<form action="/servlets/greet.jss" method="post">
<label>Name <input name="name"></label>
<button type="submit">Say hello</button>
</form>
The same greet.jss servlet can read session.params.name. For POST, these automatically prepared parameters come from the body; URL query parameters are not merged into them.
JSON requests
For a POST with Content-Type: application/json, Achieve parses the JSON value and supplies it as session.params. Native fetch() can send the request:
let response = await fetch("/servlets/profile.jss", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Ada",
role: "developer"
})
});
console.log(await response.json());
The servlet receives the parsed JSON value in session.params. In this example, the value is an object:
exports.servlet = function(session) {
session.response.setHeader(
"Content-Type",
"application/json; charset=utf-8"
);
return JSON.stringify({
message: "Hello, " + session.params.name,
role: session.params.role
});
};
Content-Type matching is case-insensitive, and parameters such as charset=utf-8 are allowed.
Malformed and large input
Invalid JSON receives 400 Bad Request, and Achieve does not invoke the servlet.
Achieve limits automatically buffered JSON and URL-encoded form bodies to 1 MiB by default. Requests exceeding that limit receive 413 Payload Too Large before the servlet runs.
Use setBufferedInputLimit() to change that limit.
Other content types and streaming
Achieve automatically parses only JSON and URL-encoded form POST bodies. For another content type, session.params is empty and application code reads the normal Node request stream through session.request. This also avoids Achieve's buffered-input limit, so the application must enforce any limits appropriate to its stream.
Buffered parsing is complete before either a synchronous or asynchronous servlet is invoked. Async servlets use the same session.params values as synchronous servlets.
See Backend: JavaScript Servlets for servlet execution and responses, the Servlet Session Object for session.params and session.request, and the Configuration Reference for input limits.