Fetch Api get params - javascript

I am trying to make a "GET" request using window.fetch, and I need to pass in a param which takes in an entire array as the value. For example, the request url should look like this
'https://someapi/production?moves=[]'
I have the following segment, which ends up in a 400 request, because the array gets evaluated to empty
let url = new URL('https://someapi/production');
let params = {moves: []};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
console.log(url);
fetch(url.href)
.then(res => res.json())
.then(val => {
console.log(val);
});
Upon inspecting the url.href looks like
https://someapi/production?moves=
where as I want it to be
https://someapi/production?moves=[]
Any suggestions on how I can achieve this?

Because the second argument of url.searchParams.append(key, params[key]) is not a string, URLSearchParams.append will result in the value being stringified. I assume that's by calling the Array.prototype.toString() method on it, which omits the array brackets.
So, you'll either need to concatenate some brackets onto that string, or call a different method (like JSON.stringify mentioned in the comments) to keep the brackets.

Related

How to pass array in the url?

I'd like to filter and want to pass an array to the url.
handleFilter = (search, page = 1) => {
const requestOption = {
method: "GET"
};
fetch("http://127.0.0.1:8000/api/home?search=" + JSON.stringify(search) + "&page=" + page, requestOption)
.then(res => res.json())
.then(data => (
this.setState({
data
})
))
};
Just want to pass the array of data to the api to call the query
I don't know if this will be what exactly you need, but I would...
a.) Join it on a strange character, and pass it as a string.
b.) On the receiving side (client or server), split on that same character.
If you want send it exactly as GET method (not Post), you can form your URL like this:
"http://127.0.0.1:8000/api/home?search[]=value1&search[]=value2&search[]=value3"
That is if you don't want send JSON string.
And what the problem with JSON version or POST method?

Unable to get a value from a json after node fetch in javascript

For My API GET operation, I use node fetch and my code is
var fetch = require('node-fetch');
const HttpProxyAgent = require('http-proxy-agent');
const HttpsProxyAgent = require('https-proxy-agent');
fetch('https://threemashery.rb.ipdesign.info/cit1/apigw/tibs/nbrmgmt/NumberManagementService/v1/RetrieveListDNForSelection?apikey=5w8anhcabembfp7tne67rhk8&userID=cpacadm&quantity=2&operatorId=3UK&orderNumber=ORD12341&numberCategory=Normal', {method: 'GET', agent: new
HttpsProxyAgent('http://10.10.104.4:50683') })
.then(resRaw=>{
return resRaw.text();
})
.then(resJson=>{
console.log(resJson);
console.log(resJson.Header);
})
And below are my both console log outputs
{"Header":{"ActivityName_T":"AS_DNLogicalResource_NM","MsgType_T":"RESPONSE","msgName":"Error occured while processing request for List DN","Source":"RetrieveListDNLogicalResourceNM","ActivityStatusEnum_T":"FAILURE","ActivityStatus_T":"rcFailure","Timestamp":"2018-07-26T14:45:14.009Z","ProviderInfo":[{"name":"b08359a6-dea1-4e34-9c47-8d5971e1a9dd1532616302405","valueType":"rcFailure","description":"Order is being modified.","Value":{"CharacteristicValue":[{"value":"FAILURE"}]}}]},"Payload":{"NotificationDetails":[{"errorCode":"rcFailure","errorDescription":"Order is being modified."}]}}
undefined
Why am I getting as undefined, while I try to take the first element? someone please help me.
Even I tried the below
console.log(resJson);
let res=JSON.stringify(resJson);
console.log(res);
But I am getting like
{"Header":{"ActivityName_T":"AS_DNLogicalResource_NM","MsgType_T":"RESPONSE","msgName":"Error occured while processing request for List DN","Source":"RetrieveListDNLogicalResourceNM","ActivityStatusEnum_T":"FAILURE","ActivityStatus_T":"rcFailure","Timestamp":"2018-07-26T14:40:40.189Z","ProviderInfo":[{"name":"4463c84f-4d38-4173-8f11-3b82b2c539a51532616029573","valueType":"rcFailure","description":"Order is being modified.","Value":{"CharacteristicValue":[{"value":"FAILURE"}]}}]},"Payload":{"NotificationDetails":[{"errorCode":"rcFailure","errorDescription":"Order is being modified."}]}}
"{\"Header\":{\"ActivityName_T\":\"AS_DNLogicalResource_NM\",\"MsgType_T\":\"RESPONSE\",\"msgName\":\"Error occured while processing request for List DN\",\"Source\":\"RetrieveListDNLogicalResourceNM\",\"ActivityStatusEnum_T\":\"FAILURE\",\"ActivityStatus_T\":\"rcFailure\",\"Timestamp\":\"2018-07-26T14:40:40.189Z\",\"ProviderInfo\":[{\"name\":\"4463c84f-4d38-4173-8f11-3b82b2c539a51532616029573\",\"valueType\":\"rcFailure\",\"description\":\"Order is being modified.\",\"Value\":{\"CharacteristicValue\":[{\"value\":\"FAILURE\"}]}}]},\"Payload\":{\"NotificationDetails\":[{\"errorCode\":\"rcFailure\",\"errorDescription\":\"Order is being modified.\"}]}}"
Why am I getting as undefined, while I try to take the first element?
You said return resRaw.text() so resJson is the text of the response.
A simple string does not have a Header property.
You need to return resRaw.json() if you want to parse the response as JSON and put the resulting object into resJson.
Even I tried the below
let res=JSON.stringify(resJson);
That's going in the wrong direction. You're taking the string and then expressing it in JSON.
You need to parse the JSON into JavaScript data.

Array undefined javascript

Hello my problem is that i get undefined , when trying to accsess the array length, but everything works fine when i try to access only the array.
this above do not works ->
console.log(this.ref_number_response[0].info.length);
This works ->
console.log(this.ref_number_response);
and this is the whole
check_ref_number: function () {
this.ref_number_response = [];
axios.get('/is_referenceNumber_free/'+this.ref_number)
.then(response => this.ref_number_response.push({
info: response.data
}));
console.log(this.ref_number_response[0].info.length);
Event.$emit('reference_added', this.ref_number_response);
},
Emit the event after you recieve the data:
check_ref_number: function () {
axios.get('/is_referenceNumber_free/'+this.ref_number)
.then(response => Event.$emit('reference_added',[{info:response.data}]));
}
The problem is that you are getting the data asynchronously, and trying to use the data before it is ready.
You said you are trying to access the the array length, but
this.ref_number_response
is the array, so the only way this console.log(this.ref_number_response[0].info.length); is going to work ( you're trying to get the info property from first element of the array length not the actual array length ) is if info were an array as well. So you'd probably need to do something like:
console.log(this.ref_number_response.length);

How to get to request parameters in Postman?

I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?
The pm.request.url.query.all() array holds all query params as objects.
To get the parameters as a dictionary you can use:
var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});
I have been looking to access the request params for writing tests (in POSTMAN). I ended up parsing the request.url which is available in POSTMAN.
const paramsString = request.url.split('?')[1];
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
console.log(params); // this is object with request params as key value pairs
edit: Added Github Gist
If you want to extract the query string in URL encoded format without parsing it. Here is how to do it:
pm.request.url.getQueryString() // example output: foo=1&bar=2&baz=3
pm.request.url.query returns PropertyList of QueryParam objects. You can get one parameter pm.request.url.query.get() or all pm.request.url.query.all() for example. See PropertyList methods.
It's pretty simple - to access YOUR_PARAM value use
pm.request.url.query.toObject().YOUR_PARAM
Below one for postman 8.7 & up
var ref = pm.request.url.query.get('your-param-name');
I don't think there's any out of box property available in Postman request object for query parameter(s).
Currently four properties are associated with 'Request' object:
data {object} - this is a dictionary of form data for the request. (request.data[“key”]==”value”) headers {object} - this is a dictionary of headers for the request (request.headers[“key”]==”value”) method {string} - GET/POST/PUT etc.
url {string} - the url for the request.
Source: https://www.getpostman.com/docs/sandbox
Bit late to the party here, but I've been using the following to get an array of url query params, looping over them and building a key/value pair with those that are
// the message is made up of the order/filter etc params
// params need to be put into alphabetical order
var current_message = '';
var query_params = postman.__execution.request.url.query;
var struct_params = {};
// make a simple struct of key/value pairs
query_params.each(function(param){
// check if the key is not disabled
if( !param.disabled ) {
struct_params[ param.key ] = param.value;
}
});
so if my url is example.com then the array is empty and the structure has nothing, {}
if the url is example.com?foo=bar then the array contains
{
description: {},
disabled:false
key:"foo"
value:"bar"
}
and my structure ends up being { foo: 'bar' }
Toggling the checkbox next to the property updates the disabled property:
have a look in the console doing :
console.log(request);
it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)
Hope this helps
Alexandre
Older post, but I've gotten this to work:
For some reason the debugger sees pm.request.url.query as an array with the items you want, but as soon as you try to get an item from it, its always null. I.e. pm.request.url.query[0] (or .get(0)) will return null, despite the debugger showing it has something at 0.
I have no idea why, but for some reason, it is not at index 0, despite the debugger claiming it is. Instead, you need to filter the query first. Such as this:
var getParamFromQuery = function (key)
{
var x = pm.request.url.query;
var newArr = x.filter(function(item){
return item != null && item.key == key;
});
return newArr[0];
};
var getValueFromQuery = function (key)
{
return getParamFromQuery(key).value;
};
var paxid = getValueFromQuery("paxid");
getParamFromQuery returns the parameter with the fields for key, value and disabled. getValueFromQuery returns just the value.

extract specific part of API response to JSON object in Javascript

I am trying to interrogate an API response from the Recognize (fashion recognition) API. The data is returned as set out below. I am trying to extract the items of attire from the following object.
Object {data: " Array↵(↵ [id] => 1309↵)↵{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}", status: 200, headers: function, config: Object, statusText: "OK"}config: Objectdata: " Array↵(↵ [id] => 1309↵)↵{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}"headers: function (name) {status: 200statusText: "OK"__proto__: Object
I have tried to access using data.data which returned the following as a string:
" Array
(
[id] => 1309
)
{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}"
I then tried to use JSON.parse to extract the data from the VufindTags. That did not work.
Is there a way to convert this into a JSON Object??
Thanks for any help!!
It looks like the vufind API is giving you PHP print_r output instead of JSON. The best thing to do would be to get them to fix their API. Failing that, you can pull the JSON-ified bits out. I had some success with this:
myObj = JSON.parse(apiOutput.slice(apiOutput.indexOf('{')))
...but I wouldn't put that into an app and call it production ready, especially when the API clearly isn't giving you what it should in the first place.

Categories

Resources