I need to create url for get which is going to accept array, how in node.js/express extract array from request? - node.js

I need to create url for get which is going to accept array, how in node.js/express extract array from request ?
I need to pass array with names which parametes I need to back from Person
model.
/api/person # here I need to pass which fields I want to see but to be generic.

One option is using a JSON format.
http://server/url?array=["foo","bar"]
Server side
var arr = JSON.parse(req.query.array);
Or your own format
http://server/url?array=foo,bar
Server side
var arr = req.query.array.split(',');

Express exposes the query parameter as an array when it is repeated more than once in the request URL:
app.get('/', function(req, res, next) {
console.log(req.query.a)
res.send(200)
}
GET /?a=x&a=y&a=z:
// query.a is ['x', 'y', 'z']
Same applies for req.body in other methods.

You can encode an array in percent encoding just "overwriting" a field, formally concatenating the values.
app.get('/test', function(req,res){
console.log(req.query.array);
res.send(200);
});
localhost:3000/test?array=a&array=b&array=c
This query will print ['a','b','c'].

Using next code:
app.use('/', (req, res) => {
console.log(req.query, typeof req.query.foo, Array.isArray(req.query.foo));
res.send('done');
});
On backend, you have two standard approaches. For next requests:
/?foo=1&foo=2
/?foo[]=1&foo[]=2
your NodeJS backend will receive next query object:
{ foo: [ '1', '2' ] } 'object' true
{ foo: [ '1', '2' ] } 'object' true
So, you can choose the way you want to. My recommendation is the second one, why? If you're expect an array and you just pass a single value, then option one will interpret it as a regular value (string) and no an array.
[I said we have two standards and is not ok, there is no standard for arrays in urls, these are two common ways that exist. Each web server does it in it's own way like Apache, JBoss, Nginx, etc]

If you want to pass an array from url parameters, you need to follow the bellow example:
Url example:
https://website.com/example?myarray[]=136129&myarray[]=137794&myarray[]=137792
To retrieve it from express:
console.log(req.query.myarray)
[ '136129', '137794', '137792' ]

Express has a tool to check if your path will match the route you are creating : Express.js route tester.
As Jose Mato says you have to decide how to structure your url:
?foo=1&foo=2
?foo[]=1&foo[]=2
The http request should look like this, if you chose method 1:
http://baseurl/api/?foo=1&foo=2
Your route should have this logic:
app.get('/api/:person', (req, res) => {
/*This will create an object that you can iterate over.*/
for (let foo of req.params.foo) {
/*Do some logic here*/
}
});

You can pass array elements separated by slashes -
GET /api/person/foo/bar/...
Define your route as '/api/person/(:arr)*'
req.params.arr will have the first parameter.
req.params[0] will have the rest as string.
You split and create an array with these two.
app.get('/api/person/(:arr)*', function(req, res) {
var params = [req.params.arr].concat(req.params[0].split('/').slice(1));
...
});
GET /api/person/foo
params = ["foo"]
GET /api/person/foo/bar
params = ["foo", "bar"]
...

Here use this, '%2C' is the HTML encoding character for a comma.
jsonToQueryString: function (data) {
return Object.keys(data).map((key) => {
if (Array.isArray(data[key])) {
return encodeURIComponent(`${key}=${data[key].map((item) => item).join('%2C')}`);
}
return encodeURIComponent(`${key}=${data[key]}`);
}).join('&');
}
To access the query params
const names = decodeURIComponent(req.query.query_param_name);
const resultSplit = names.split(',');

Theres a problem when the array param contains only one value, because then it behaves like a simple string. Or when it doesn't contain any value.
Eg.:
?arrayParam=5
?
?arrayParam=5&arrayParam=6
Here's a function that always extracts the param with the given name, as an array:
export function extractArrQueryParams(
req: express.Request,
paramName: string
) {
let param = req.query[paramName];
let returnArray = [];
if (Array.isArray(param)) {
for (let e of param) {
returnArray.push(e);
}
} else {
if (param) {
returnArray.push(param);
}
}
return returnArray;
}

Related

How do I access content from JSON string?

I am receiving a JSON object from the backend now I just want "result" array only in my template variable in my angular application from it.
{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}
Try with
variable_name["result"].
Try with
var data = response from the backend
var result = data.result;
$var = '{"result":[{"name":"Sunil Sahu","mobile":"1234567890","email":"abc#gmail.com","location":"Mumbai","Age":"19"}],"stats":200}';
If your $var is string, you need to turn it to "array" or "object" by json_decode() function
object:
$var_object = json_decode($var); //this will get an object
$result = $var_object->result; //$result is what you want to get
array:
$var_array = json_decode($var, true); //this will get an array
$result = $var_array['result']; //$result is what you want to get
Else if $var is object, direct use
$result = $var->result; //$result is what you want to get
As result is an array of objects, you can either use any loop to extract key value pair or you can directly access the array using index value.
var results = data["result"] // this would return an array
angular.forEach(results, function(value, key) {
//access key value pair
});
For accessing results in HTML, ng-repeat directive can be used.
Your question didn't explain further, but in the simple way try this :
const stringJson = `{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}`
const obJson = JSON.parse(stringJson);
console.log(obJson.result);

Verify and select the right object in an array thanks to a find method which will match with a param json

I need some help,
I've got a json with some parameters inside of it, actually 2 but one day we may add some more in it.
I want to find between some object in an array the right one thanks to all parameters in the json
Am i using the right method ?
to be clearer, i want the param.t to match with the element.t, and the param.tid to match with the element.tid and if moving forward one more parameter cd1 is added to the JSON, this param.cd1 will match with element.cd1
thanks for the time !
const array1 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
for (let [key, value] of Object.entries(param)) {
console.log(`${key}: ${value}`);
}
const obj = array1.find(element => element.t == param.t);
If I am following correctly, you want to compare an array of objects to an object and based on some keys in 'param' object you want to filter out your array1.
const array2 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param1 = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
const test = array2.find(checkExist);
const checkExist = el => {
return el.t == param1.t && el.tid == param1.tid; // here you can add your keys in future
}

How do I filter keys from JSON in Node.js?

I'm trying to select certain keys from an JSON array, and filter the rest.
var json = JSON.stringify(body);
which is:
{
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
}
Want I want:
{
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
}
}
I've checked out How to filter JSON data in node.js?, but I'm looking to do this without any packages.
Now you can use Object.fromEntries like so:
Object.fromEntries(Object.entries(raw).filter(([key]) => wantedKeys.includes(key)))
You need to filter your obj before passing it to json stringify:
const rawJson = {
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
};
// This array will serve as a whitelist to select keys you want to keep in rawJson
const filterArray = [
"FirstName",
"typeform_form_submits",
];
// this function filters source keys (one level deep) according to whitelist
function filterObj(source, whiteList) {
const res = {};
// iterate over each keys of source
Object.keys(source).forEach((key) => {
// if whiteList contains the current key, add this key to res
if (whiteList.indexOf(key) !== -1) {
res[key] = source[key];
}
});
return res;
}
// outputs the desired result
console.log(JSON.stringify(filterObj(rawJson, filterArray)));
var raw = {
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
}
var wantedKeys =["FirstName","typeform_form_submits" ]
var opObj = {}
Object.keys(raw).forEach( key => {
if(wantedKeys.includes(key)){
opObj[key] = raw[key]
}
})
console.log(JSON.stringify(opObj))
I know this question was asked aways back, but I wanted to just toss out there, since nobody else did:
If you're bound and determined to do this with stringify, one of its less-well-known capabilities involves replacer, it's second parameter. For example:
// Creating a demo data set
let dataToReduce = {a:1, b:2, c:3, d:4, e:5};
console.log('Demo data:', dataToReduce);
// Providing an array to reduce the results down to only those specified.
let reducedData = JSON.stringify(dataToReduce, ['a','c','e']);
console.log('Using [reducer] as an array of IDs:', reducedData);
// Running a function against the key/value pairs to reduce the results down to those desired.
let processedData = JSON.stringify(dataToReduce, (key, value) => (value%2 === 0) ? undefined: value);
console.log('Using [reducer] as an operation on the values:', processedData);
// And, of course, restoring them back to their original object format:
console.log('Restoration of the results:', '\nreducedData:', JSON.parse(reducedData), '\nprocessedData:', JSON.parse(processedData));
In the above code snippet, the key value pairs are filtered using stringify exclusively:
In the first case, by providing an array of strings, representing the keys you wish to preserve (as you were requesting)
In the second, by running a function against the values, and dynamically determining those to keep (which you didn't request, but is part of the same property, and may help someone else)
In the third, their respective conversions back to JSON (using .parse()).
Now, I want to stress that I'm not advocating this as the appropriate method to reduce an object (though it will make a clean SHALLOW copy of said object, and is actually surprisingly performant), if only from an obscurity/readability standpoint, but it IS a totally-effective (and mainstream; that is: it's built into the language, not a hack) option/tool to add to the arsenal.

Passing path parameters in axios

I am using Axios with NodeJs and trying to pass path parameters in axios.get() method. For example, if URL is url = '/fetch/{date}', I want to replace {date} with the actual date while calling axios.get(url).
I went through the source code on Github and StackOverflow, but couldn't find any method.
Is it possible to keep URLs with parameters as a placeholder and replace them while actually calling the get method of Axios?
Axios doesn't have this feature and it looks like the team don't want to add it.
With credit to previous responders for inspiration, to me this seems like the solution closest to what you (and me) are looking for:
1 - Where you want to store all your URLs and their parameters, define them as functions which use a template string to return the composed URL:
export var fetchDateUrl = (date) => `/fetch/${date}`;
If you need any type-specific formatting of the value being concatenated into the URL, this function is a good place to do it.
2 - Where you want to make the request, call the function with the correct parameters:
import { fetchDateUrl } from 'my-urls';
axios.get(fetchDateUrl(someDateVariable))...;
Another variation, if you really like the idea of naming the parameters at the call site, you can define the URL function to destructure an object like this:
var fetchDateUrl = ({date}) => `/fetch/${date}`;
which you'd then use like this:
axios.get(fetchDateUrl({date: someDateVariable}));
Use template strings
url = `/fetch/${date}`
Or just tag it on
url = '/fetch/'+ date
I think using axios interceptors is better to do this :
//create your instance
const instanceAxios = axios.create({
baseUrl: 'http://localhost:3001'
]);
instanceAxios.interceptors.request.use(config => {
if (!config.url) {
return config;
}
const currentUrl = new URL(config.url, config.baseURL);
// parse pathName to implement variables
Object.entries(config.urlParams || {}).forEach(([
k,
v,
]) => {
currentUrl.pathname = currentUrl.pathname.replace(`:${k}`, encodeURIComponent(v));
});
const authPart = currentUrl.username && currentUrl.password ? `${currentUrl.username}:${currentUrl.password}` : '';
return {
...config,
baseURL: `${currentUrl.protocol}//${authPart}${currentUrl.host}`,
url: currentUrl.pathname,
};
});
// use like :
instanceAxios.get('/issues/:uuid', {
urlParams : {
uuid: '123456789'
}
})
For typescript users, you will need to add this, in one of your .d.ts
declare module 'axios' {
interface AxiosRequestConfig {
urlParams?: Record<string, string>;
}
}
( this is a POC, not really tested, doesn't hesitate if you see something wrong )
You can use template strings ie:
let sellerId = 317737
function getSellerAnalyticsTotals() {
return axios.get(`http://localhost:8000/api/v1/seller/${sellerId}/analytics`);
}
Given some API /fetch/${date} you likely want to wrap your axios call in a function.
const fetchData = (date) => axios.get(`/fetch/${date}`);
fetchData(dateObject.toFormat('yyyy-mm-dd'))
.then(result => { ... });
This requires the calling code to format date correctly however. You can avoid this by using a DateTime library that handles date string parsing and do the format enforcement in the function.
const fetchData = (date) => axios.get(`/fetch/${date.toFormat('yyyy-mm-dd')}`);
fetchData(dateObject)
.then(result => { ... });
you can do like this:
getProduct = (id) => axios.get(`product/${id}`);
I always do it like this:
const res = await axios.get('https://localhost:3000/get', { params: { myParam: 123 } });
I find this to be much clearer than template strings.
More explanation here

How Express routes similar url links?

Developing web app with node.js and express.
I have following two urls to distinguish:
/api/v1/source?id=122323
/api/v1/source?timestamp=1555050505&count=10
I come up a naive solution. I leave such similar urls to one route method and use if eles to specify solutions, i.e:
if(id){
//solution with id
}
if(timestamp&&count){
//solution with timestamp and count but without id
}
Apparently, this is not clean. Because in the future,I may want to add new field which will make this router huge and ugly.
So How can I overcome this? Or to change url structure.I want to build a Restful api.
Try to put together all the properties in a list and use Array#every to check if all the values in Array evaluates to true.
Maybe something like this:
(( /* req, res */)=>{
// Dummy express Request Object
const req = {
params : {
//id : '123',
count : 10,
timestamp : 1555050505,
newParameter : 'whatever value'
}
}
let { params } = req;
let {
id
, count
, timestamp
, newParameter
} = params;
if(id){
console.log('Action with id');
return;
}
let secondConditionArray = [
count, timestamp, newParameter
];
if( secondConditionArray.every(Boolean) ){
console.log('Second Action')
} else {
console.log('Some values are no truthy')
}
})()
You can get Url parameters with req.params
if(req.params.id){
//solution with id
}
if(req.params.timestamp && req.params.count){
//solution with timestamp and count but without id
}

Resources