How to remove and add query parameters using JavaScript ?

We are working on a javascript file that will manipulate query parameters of an incoming request based on certain requirements.

In general, can you tell me how to add and remove query parameters using only javascript and not the assign message policy?

Solved Solved
0 1 12.3K
1 ACCEPTED SOLUTION

We can use the context.setVariable and context.removeVariable APIs to add and remove the query parameters from the request via the JavaScript policy. Below are the code snippets that suggests how it can be done.

  1. To add a query parameter to the request object
    var count = 100;
    context.setVariable("request.queryparam.count", count);
    
  2. To remove a specific query parameter from the request object
    var username = 'Username'; 
    context.removeVariable("request.queryparam." + username); 
  3. To remove all query parameters from the request object
    // Print the request before removing the query parameter
    context.setVariable("MyRequest1", request);
    
    // Get all the query parameter names
    var queryParamNames = context.getVariable('request.queryparams.names');
    
    //convert it to string array.
    
    queryParamNames = queryParamNames.toArray();
    
    for (var i = 0; i < queryParamNames.length; i++) {
       print("queryParamName = " + queryParamNames[i]);
       // Remove the query parameter from the request
       context.removeVariable("request.queryparam." + queryParamNames[i]);
    }
    
    // Print the request after removing the query parameters
    context.setVariable("MyRequest2", request);
    

View solution in original post

1 REPLY 1

We can use the context.setVariable and context.removeVariable APIs to add and remove the query parameters from the request via the JavaScript policy. Below are the code snippets that suggests how it can be done.

  1. To add a query parameter to the request object
    var count = 100;
    context.setVariable("request.queryparam.count", count);
    
  2. To remove a specific query parameter from the request object
    var username = 'Username'; 
    context.removeVariable("request.queryparam." + username); 
  3. To remove all query parameters from the request object
    // Print the request before removing the query parameter
    context.setVariable("MyRequest1", request);
    
    // Get all the query parameter names
    var queryParamNames = context.getVariable('request.queryparams.names');
    
    //convert it to string array.
    
    queryParamNames = queryParamNames.toArray();
    
    for (var i = 0; i < queryParamNames.length; i++) {
       print("queryParamName = " + queryParamNames[i]);
       // Remove the query parameter from the request
       context.removeVariable("request.queryparam." + queryParamNames[i]);
    }
    
    // Print the request after removing the query parameters
    context.setVariable("MyRequest2", request);