0

I have a url which takes an array of topicName query like this

localhost:3000/api/?topicName=mobile&topicName=website

and sometimes topicName only has one value like this

localhost:3000/api/?topicName=mobile

and below is how I use that query values in node JS

let topicNameArray = [];
topicNameArray = req.query.topicName
let value = topicNameArray.map(function(e) {
return new RegExp(e, "i");
})

The problem I am facing is when the array query only has one value, my app will receive this message

"message": "topicNameArray.map is not a function

Can anyone suggest me a solution to deal with this problem? Thank you so much!

1
  • You can use console.log(topicNameArray) to check topicNameArray is array or string. Commented Jun 16, 2018 at 0:26

3 Answers 3

1

I believe you need to reform your querystring to mitigate the error you are experiencing.

Currently I think you have a query string like such: localhost:3000/api/?topicName=mobile&topicName=website Here you have one query argument topicName and this is essentially a string. So when you have multiple instance of topicName key in your querystring you should have been replacing the the value at this key with the last instance of it in the querystring. So to send an array of values use the querystring structure as following: localhost:3000/api/?topicName[]=mobile&topicName[]=website (notice the square brace.)

Later you can check if the query argument is an array or not. You can use Array.isArray function for that. Then you can perform your exception handling on later parts.

Sign up to request clarification or add additional context in comments.

1 Comment

The Array.isArray is what I need. Thanks!
0

you could check if topicName is an array using one of the following and convert it to an array like this

topicNameArray = req.query.topicName
if(req.query.topicName.constructor !== Array) {
   topicNameArray = [req.query.topicName];
}

Or like this,

topicNameArray = req.query.topicName
if(!topicNameArray.length) { // only arrays have length property
   topicNameArray = [req.query.topicName];
}

Comments

0

Currently, topicNameArray is being reassigned to req.query.topicName which is actually a string when only one topicName is given. You can check the type of req.query.topicName and if its a string turn it into an array like so:

let topicNameArray = req.query.topicName;   // assume its an array
if (typeof topicNameArray === "string")  { // check if it's a string
  topicNameArray = [req.query.topicName];   // convert to array
}

or if you prefer the look of the ternary operator:

let topicName = req.query.topicName;
let topicNameArray = (typeof topicName === "string") ? [topicName] : topicName;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.