parameters snippets

How to parse request parameters with JavaScript

Tagged javascript, jquery, request, parameters, url, parse  Languages javascript

Code:

var Request = {
    parameter: function(name) {
      return this.parameters()[name];
    },
    parameters: function(uri) {
      var i, parameter, params, query, result;
      result = {};
      if (!uri) {
        uri = window.location.search;
      }
      if (uri.indexOf("?") === -1) {
        return {};
      }
      query = uri.slice(1);
      params = query.split("&");
      i = 0;
      while (i < params.length) {
        parameter = params[i].split("=");
        result[parameter[0]] = parameter[1];
        i++;
      }
      return result;
    }
  };

Examples:

// ?query=test
var query = Request.parameter('query');

var parameters = Request.parameters();
// This works too
var query = parameters.query;
// And this
var query = parameters['query'];

// Replacing a parameter is easy with jQuery
parameters Request.parameters();
// change sort order
parameters.order = 'new-world-order'
new_parameters = $.param(parameters)
url = window.location.pathname + "?" + new_parameters

How to filter post parameters with nginx and the Perl module

Tagged nginx, post, perl, parameters, filter  Languages apacheconf

This example demonstrates how to inspect and filter POST parameters sent through nginx to a backend server with Perl:

nginx => filter (perl) => backend

This could also be done with the Lua module.

nginx.conf:

http {
    perl_modules  /tmp;
    perl_require  filter.pm;

    server {
        # The action we want to filter
        location = /bananas/create {
          perl  filter::handler;
        }
        # The backend server
        location = /backend {
            internal; # Only allowed internally
            proxy_pass http://backend/bananas/create;
        }
        # The action that handles blocked requests
        location = /blocked {
            internal;
            perl filter::block;
        }
}

/tmp/filter.pm:

package filter;
use nginx;

# Handle request
sub handler {
  my $r = shift;
  if ($r->has_request_body(\&checkRequest)) {
    return OK;
  }
  return OK;
}

# Print a message
sub blocked {
  my $r = shift;
  $r->send_http_header("text/html");
  $r->print("Blocked...\n<br/>");
  $r->rflush;
  return OK;
}

# Check request for invalid parameter
sub checkRequest {
  my $r = shift;
  my $body = $r->request_body;
  # Try to detect invalid POST parameters
  if ($body =~ /credit_card=/) {
     $r->internal_redirect("/blocked"); # Redirect to /blocked
  } else {
     $r->internal_redirect("/backend"); # Redirect to /backend
  }
  return OK;
}

1;
__END__