Erbix

Home > Javascript Server-side Reference > JSGI

A JSGI (JavaScript Gateway Interface) function receives standard input parameters and outputs the result under a specific format for the purpose of interacting with a web-server in order to process incoming HTTP requests.

Erbix implements JSGI 0.3.

JSGI Input

A JSGI function's input consists of a single parameter called request. It contains different keys that indicate details about the incoming request. The path of the URL requested by the client can be found in request.pathInfo.

JSGI Output

A JSGI function's output consists in a hash containing 3 keys:

  • status - numeric field indicating the status code of the reply.
  • headers - hash of key/value pairs reflecting header names and corresponding values in the reply.
  • body - array of strings representing the body of the reply.

Hello World Example

The following code is a Hello World implementation in JSGI which displays the text Hello World for the homepage and returns the error code 404 HTTP Not Found for other requests.


  function jsgiHandler(request) {
    if (request.pathInfo !== "/") {
      return {
        status: 404,
        headers: {
          "Content-Type": "text/plain"
        },
        body: ["Page not found."]
      };
    }

    return {
      status: 200,
      headers: {
        "Content-Type": "text/plain"
      },
      body: ["Hello World!"]
    };
  };

Retrieving GET Parameters

The JSGI specification doesn't mention an API that could be used in order to parse parameters from the query string.

In order to do this, you can use the ringo/webapp/parameters module like shown in the example below:


  var ringoParameters = require("ringo/webapp/parameters");
  var queryParams = {};

  ringoParameters.parseParameters(request.queryString, queryParams, "utf-8");
  if (queryParams.parameterName === desiredValue) {
    ...
  }

(the request variable is the input parameter from the JSGI function).

Retrieving Any Parameter

You can retrieve parameters generically (no matter what was the method used in order to send them - GET, POST...) by using the servletRequest object placed in the request's env member, which offers a convenient getParameter method.


  var httpRequest = request.env.servletRequest;
  var parameterValue = httpRequest.getParameter("parameterName");
  if (parameterValue !== null) {
    // The parameter exists - do something with the value.
    ...
  }

(the request variable is the input parameter from the JSGI function).

Reference Specification

The complete reference specification is available at CommonJS's website.