Get an automatic list of ExpressJS params - regex

I am trying to get a list of all of the parameters in a path from a get request.
app.get('/*',function(req, res) {
console.log(req.params[0]);
res.send('testing');
});
However, when I go to the url localhost/test/test1, the params[0] object is 'test/test1'.
Is there any way to make it split the url in to params without doing '/*/*'. I want to be able to put in as many values as I need without worrying about naming or counting them.
The ideal input/output would be:
URL: localhost/arg1/arg2/arg3
params[0] = 'arg1'
params[1] = 'arg2'
params[2] = 'arg3'
Thanks.

A simple split will work:
var splitParams = params[0].split('/');

Related

Trying to get two postman.setNextRequest (not chained) or two Actions in Workspace

I’m quite new to postman (and coding) and was trying to find and piece together many snippets of scripts to make it work the way I want.
What I want is very simple: I have a list of IDs that I want to make a POST in each of them, get one of the responseBody as a variable and do another POST. I think I’m close but I can’t manage to get it to work.
I’ve tried:
Two POST request in the same Collection and running the collection.
In the first request I have a POST to
https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
On the Pre-request Script tab:
var orderids = pm.environment.get(“orderids”);
if (!orderids) {
orderids = [“bc46bf79-2846-44ed-ac4d-78c77c92ccc8”,“81aacc33-1ade-41a3-b23e-06b03b526b8f”];
}
var currentOrderId = orderids.shift();
pm.environment.set(“orderid”, currentOrderId);
pm.environment.set(“orderids”, orderids);
On the Tests tab:
var orderids = pm.environment.get(“orderids”);
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“invoice.id”, jsonData.invoice.id);
postman.setNextRequest(“Create invoice”);
} else {
postman.setNextRequest(null);
}
invoice.id is a environment variable populated with the response body of the first action/post and then using the variable on the second action/post.
And then the second request would be a POST to
https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
Of course this doesn’t work. Either it doesn't run the second request in the collection or it doesn't do the loope to more than 1 ID on the list.
So I thought that putting the second POST inside the first one would solve it. But I had no luck.
Can please someone help me?
I have tried mentioned use case with sample API's provided by POSTMAN.
Can you try it?
First POST Method Request : https://postman-echo.com/post
Pre-request Script of first POST method
var orderids = pm.environment.get("orderids");
if(!orderids ){
orderids = ["bc46bf79-2846-44ed-ac4d-78c77c92ccc8","81aacc33-1ade-41a3-b23e-06b03b526b8f"];
}
var currentOrderId = orderids.shift();
pm.environment.set("orderid", currentOrderId);
pm.environment.set("orderids", orderids);
Tests Tab of first POST Method
var orderids = pm.environment.get("orderids");
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.headers.host);
postman.setNextRequest("Test1");
} else {
postman.setNextRequest(null);
}
Second POST Method Reqeust: https://postman-echo.com/post?key={{invoice.id}}
After executing the above collection it will set orederids and invoice.id value in environment variables and then it will call next POST Method.
Hope this will help you.
Thanks #HalfBloodPrince, from the Postman Echo it worked but in my case it doesn't :S
What I manage to get it working was using a Json file as a list of Orderids.
In that case I've separated all requests.
Request1 - https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
Tests tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.invoice.id);
Request2 - https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
That way everything is in a neat and organized way.
Thanks

How to build a Postman url query with Pre-request Scripts

I'm trying to use a pre-request script to build out a request object based on data pulled from a CSV file. The problem is that the request seems to be set in stone prior to the pre-request script being run. That would seem to make this a mid-request script almost rather than a pre-request.
My code is as follows:
if(ipList === undefined) ipList = "1.2.3.4,2.3.4.5,123.234.345.465";
let ips = ipList.split(',');
let queryArray = [];
for( i=0; i<ips.length; i++){
queryArray.push({ "key": "ip", "value": ips[i] });
}
console.log(queryArray);
pm.request.url.query = queryArray;
console.log(pm.request);
When I hardcode a url query variable in the request to equal 4.3.2.1, the pm.response.url object like this:
pm.request.url.query[0] = {key:"ip", value:"4.3.2.1"}
Note that the url.query[0] part of the object matches the parameter in the actual get request.
When I change the value of pm.request.url.query to equal the new query array, however as you can see here, the query array is set correctly, but the parameters are not appended to the request URL.
So unless I'm doing something wrong, it appears that the request is immutable even to the pre-request scripts.
So my question is this:
Is there a way to modify the url params of a request prior to making the request?
BTW: I know that is might seem odd to have multiple params with the same key in a query, but that's the way this API works and hard coding multiple ip addresses in the query works just fine.
You could just assign a new value to pm.request.url.
Here I had some query params already in the URL, which I had to edit:
const urlSplit = request.url.split('?');
const paramsString = urlSplit[1]; // the second part actually represents the query string we need to modify
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
params.bla = params.bla + 'foobar';
newQueryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
pm.request.url = urlSplit[0] + '?' + newQueryString;
In the end, I just constructed a new URL, using the first part of the previous one & the query string with the edited bla parameter.
This seemed to work for me--it didn't change what the UI shows the query string is, but it changed what the actual request was (looking at the console log)
pm.request.url.addQueryParams(["a=1", "b=2"])
pm.request.url.query.remove("b")
I have some parameters called "script_loginAs" etc... named such that people on my team know the parameter is evaluated and not sent.

Postman - How to store multiple values from a response header in a var or just be able to see them

Using a GET in postman with the URL posted below, I am able to store the entire response header in question with all of its data in a var, the issue for me is how do I verify the pieces of data inside that var
here is my URL
http://localhost/v1/accounts?pageNumber=1&pageSize=2
[
using postman I am able to get the above in a var
var XPaginationData = postman.getResponseHeader(pm.globals.get("PaginationHeader"));
pm.globals.set("XPaginationData", XPaginationData);
is there a way to get the individual values inside the response header X-Pagination stored in a different var to assert later
using this in postman
pm.globals.set("XPaginationData", JSON.stringify(pm.response.headers));
console.log(JSON.parse(pm.globals.get('XPaginationData')));
console.log(JSON.parse(pm.globals.get('XPaginationData'))[4].value);
I get
how would i go about getting "TotalCount" for example
BIG EDIT:
thanks to a coworker, the solution is this
//Filtering Response Headers to get PaginationHeader
var filteredHeaders = pm.response.headers.all()
.filter(headerObj => {
return headerObj.key == pm.globals.get("PaginationHeader");
});
// JSON parse the string of the requested response header
// from var filteredHeaders
var paginationObj = filteredHeaders[0].value;
paginationObj = JSON.parse(paginationObj);
//Stores global variable for nextpageURL
var nextPageURL = paginationObj.NextPageLink;
postman.setGlobalVariable("nextPageURL", nextPageURL);
You could use JSON.stringfy() when saving the environment variable and then use JSON.parse() to access the different properties or property that you need.
If you set a global variable for the response headers like this:
pm.globals.set('PaginationHeader', JSON.stringify(pm.response.headers))
Then you can get any of the data from the variable like this:
console.log(JSON.parse(pm.globals.get('PaginationHeader'))[1].value)
The image shows how this works in Postman. The ordering of the headers returned in the console is inconsistent so you will need to find the correct one to extract data from the X-Pagination header
Looks like an issue with Postman itself.
The only solution that worked for me was to stringify & parse the JSON again, like this:
var response = JSON.parse(JSON.stringify(res))
After doing this, the headers and all other properties are accessible as expected.

Query parameters for GET requests using Akka HTTP (formally known as Spray)

One of the features of Akka HTTP (formally known as Spray) is its ability to automagically marshal and unmarshal data back and forth from json into case classes, etc. I've had success at getting this to work well.
At the moment, I am trying to make an HTTP client that performs a GET request with query parameters. The code currently looks like this:
val httpResponse: Future[HttpResponse] =
Http().singleRequest(HttpRequest(
uri = s"""http://${config.getString("http.serverHost")}:${config.getInt("http.port")}/""" +
s"query?seq=${seq}" +
s"&max-mismatches=${maxMismatches}" +
s"&pam-policy=${pamPolicy}"))
Well, that's not so pretty. It would be nice if I could just pass in a case class containing the query parameters, and have Akka HTTP automagically generate the query parameters, kind of like it does for json. (Also, the server side of Akka HTTP has a somewhat elegant way of parsing GET query parameters, so one would think that it would also have a somewhat elegant way to generate them.)
I'd like to do something like the following:
val httpResponse: Future[HttpResponse] =
Http().singleRequest(HttpRequest(
uri = s"""http://${config.getString("http.serverHost")}:${config.getInt("http.port")}/query""",
entity = QueryParams(seq = seq, maxMismatches = maxMismatches, pamPolicy = pamPolicy)))
Only, the above doesn't actually work.
Is what I want doable somehow with Akka HTTP? Or do I just need to do things the old-fashioned way? I.e, generate the query parameters explicitly, as I do in the first code block above.
(I know that if I were to change this from a GET to a POST, I could probably to get it to work more like I would like it to work, since then I could get the contents of the POST request automagically converted from a case class to json, but I don't really wish to do that here.)
You can leverage the Uri class to do what you want. It offers multiple ways to get a set of params into the query string using the withQuery method. For example, you could do something like this:
val params = Map("foo" -> "bar", "hello" -> "world")
HttpRequest(Uri(hostAndPath).withQuery(params))
Or
HttpRequest(Uri(hostAndPath).withQuery(("foo" -> "bar"), ("hello" -> "world")))
Obviously this could be done by altering the extending the capability of Akka HTTP, but for what you need (just a tidier way to build the query string), you could do it with some scala fun:
type QueryParams = Map[String, String]
object QueryParams {
def apply(tuples: (String, String)*): QueryParams = Map(tuples:_*)
}
implicit class QueryParamExtensions(q: QueryParams) {
def toQueryString = "?"+q.map{
case (key,value) => s"$key=$value" //Need to do URL escaping here?
}.mkString("&")
}
implicit class StringQueryExtensions(url: String) {
def withParams(q: QueryParams) =
url + q.toQueryString
}
val params = QueryParams(
"abc" -> "def",
"xyz" -> "qrs"
)
params.toQueryString // gives ?abc=def&xyz=qrs
"http://www.google.com".withParams(params) // gives http://www.google.com?abc=def&xyz=qrs

create path helper, pass hash to handlebars helper or concatenate string

I was looking for a way to create a path helper in handlebars which generates a url to a specific page. I need to be able to pass a route name and the params needed to generate the route. SO first i was looking to pass a hash to the helper ... but this isn't possible because you can't create this inside the handler template. Now the syntax is like this:
{{{path 'some_path_name' 'foo=bar' }}}
and this seems to work but now i have an issue with that i can't concatenate strings inside the template. Any idea what's the best way to do this? The only option i see now is that i create the params inside my javascript code ... but i don't really like this, i wan't to be able to specify it in the template.
I have a mapping somewhere which maps some_path_name to /path-name/:foo ... so i want the path helper to create /path-name/bar.
kind regards,
Daan
This code should work, but you have to add some extra validation.
var routes = {
'some_path_name': '/path-name/:foo'
};
Handlebars.registerHelper('path', function (routeName, options) {
var route,
params;
if (!routes.hasOwnProperty(routeName)) return;
route = routes[routeName];
params = options.hash;
for (var param in params) {
var value = params[param];
route = route.replace(':'+ param, value);
}
return route;
});