What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL:

https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc

The parameter values can vary.

This is the code snippet I use:

getDataPlayer(payload) {
    let params
    if(payload.countryId && payload.clubId && payload.playerName)
      params = `countryId=${payload.countryId}&clubId=${payload.clubId}&playerName=${payload.playerName}`

    return axios.get(`https://my-website.com/api/players?${params}`)
      .then(response => {
        return response.data
      })
},

When I console.log(payload), the output appears as follows:

{countryId: "1", clubId: "2", playerName: "ronaldo"}

The payload is adaptable and can be:

{countryId: "1", clubId: "2"} or

{playerName: "ronaldo"}

Is there a more straightforward approach, or do I need to include multiple conditions in the getDataPlayer method?

Answer №1

To properly encode a query string parameter, you can utilize the encodeURIComponent function. Utilize Array.map to iterate over the keys and then join the final result using Array.join as shown below:

 let params = Object.keys(payload).map(el => `${el}=${encodeURIComponent(payload[el])}`).join('&')

If your payload is

{countryId: "1", clubId: "2", playerName: "ronal do "}
, the params will be
"countryId=1&clubId=2&playerName=ronal%20do%20"
and can be passed to the request correctly.

Answer №2

For those interested, the npm module query-string can be utilized. Check out the link here: https://www.npmjs.com/package/query-string.

This module allows for easy conversion of a JSON object into properly structured search parameters. It also offers encoding functionality.

Answer №3

function createSearchQuery(data) {
  var searchParams = '';

  if (data.countryId && data.countryId.trim().length) searchParams += `countryId=${encodeURIComponent(data.countryId.trim())}&`;

  if (data.clubId && data.clubId.trim().length) searchParams += `clubId=${encodeURIComponent(data.clubId.trim())}&`;

  if (data.playerName && data.playerName.trim().length) searchParams += `playerName=${encodeURIComponent(data.playerName.trim())}`;

  console.log(searchParams);
  return searchParams;
}

createSearchQuery({countryId: "1", clubId: "2", playerName: "ronaldo"});

createSearchQuery({countryId: "1", clubId: "2"});

createSearchQuery({playerName: "ronaldo"});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

Creating CSS animation for the most recent element that has been dynamically inserted using JavaScript and Vue.js

After adding a new div with Vue, I noticed that the opacity effect is being applied to the previous element instead of the newly added one. I want the effect to always appear on the latest element added at index 0. What could be causing this issue? Here i ...

Delaying Ajax request

I've encountered some strange behavior. After the initial ajax call triggered by selecting a city from a dropdown menu, I then have a continuous ajax call on a delay. The first call stores the selected city value in a global variable. $('.sele ...

Utilizing AJAX and JSF to implement automatic capitalization of letters

As a newcomer to AJAX, I am eager to implement a feature that automatically converts input text into capital letters after the keyup event. Can anyone guide me on how to achieve this using AJAX in conjunction with JSF? ...

What are the steps for utilizing a button instead of an input field that is not within a form?

I need assistance with setting up a navbar with a button that will submit a form in the body with the ID of album_form. Can anyone provide suggestions for what to include in the onclick attribute to achieve this functionality? <body> <header& ...

Firebase Stripe extension encountering issues with cross-origin resource sharing

I am currently developing an app using Vue 3 with Firebase and the Stripe extension. I'm facing a CORS issue when trying to access a customer portal through a cloud function. Below is the code snippet from my Vue app: <script> import { getFunct ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

Regular expression that can be used to extract information from a text file by filtering and returning only

When I open a text file, it contains several lines like the examples below. surname australia enter name j.jonhs enter name j.cause enter name f.london enter I am seeking assistance to modify the code snippet below so that it captures the first line m ...

What is the best way to enable a disabled MUI MenuItem within a table that is being mapped, based on a specific item in the

In my table, I have a mapped object of users: {users.map((user,index) => { <TableRow key={index}> ... The final cell in the table contains a button that is linked to an MUI Menu. One of the menu items should be disabled if a specific aspect of ...

Attempting to display a v-data-table inside a v-dialog results in rendering issues

I'm currently working on incorporating a v-data-table in a v-dialog <v-dialog max-width = '600px' v-model = 'dialog'> <v-card> <v-card-title> <span class = "headline"> Reconstru ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Unexpected quirks in Canvg conversion: Strange behavior observed while utilizing a fill URL

I am attempting to use the canvg javascript library to convert an svg to canvas. Within the original svg, there is a rectangle with a fill attribute that references a svg pattern. However, when I convert the svg to canvas using canvg: canvg(document.getE ...

Is it acceptable to use "string" as a variable name in JavaScript?

Any tips on getting the code below to function properly? var x = 'name'; After that, I want to utilize the value inside x like a variable and assign it so that when I call for NAME, I get this outcome: var name = 'NAME'; Can this be ...

Is it possible to utilize a variable as a column name in MySQL when working with Express?

At the moment, I am encountering an issue where the table name is surrounded by quotation marks as it is a string. This causes the server to crash. const update = 'the name of my column'; const UpdateQuery = `UPDATE scores SET ${mysql.escap ...

Long taps do not activate the context menu in the mobile interface, as noted in the Google Maps API

During the development of my project, I encountered an issue with the Google Maps API not functioning correctly on mobile devices. I am utilizing GMaps.js, but even that example does not properly support right-click (long tap event). Here is a snippet of ...

Nodejs cookie settings

I am currently working on a small petition project and I want to implement a feature where a user who signs the petition will have a cookie set so that when they try to access the page again, they are redirected to a "thanks page". If the user has not sign ...

Tips on ensuring that jQuery remains accessible following an AJAX request

jQuery(function ($) { $('input.adud').on('click', function() { var thisdiv = $(this).parents('div').attr("id"); var thisform = $(this).parents('form').attr("id"); var thistable = $(this).p ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...