Axios appends square brackets at the end of the parameter name

Utilizing vuejs in combination with axios and a Django server presents a challenge. The server requires parameters to be passed as travelers, but when using axios to send this data, it appends [] at the end resulting in travelers[].

Is there a way to prevent this behavior?

Here is an example snippet of the code:

Within the VueJS instance, we have:

data = {
        filter:{
            travelers:[],
            order:...,
...

The travelers variable can either be an array of ids or an empty array. Even though it is defined as travelers, when sent via axios, it adds [] automatically.

This part of the code generates the issue:

loadOrders: function () {
                        axios.get(this.list_orders_url, {
                            params: this.filter
                        }).then(function (response) {
                            app.orders = response.data;
                        }).catch(function (error) {
                            console.log(error); // todo
                        })
                    },

Effectively, it results in travelers[]=1&travelers[]=2 being included in the query string.

Answer №1

Utilize the paramsSerializer feature even with null indexes included

{
  params,
  paramsSerializer: { indexes: null }
}

Answer №2

To make sure everything runs smoothly, you need to define the serialization logic in the paramsSerializer property :) For this example, I opted for using query-string, but feel free to choose any other module or your own custom method.

const queryString = require('query-string');

loadOrders: function () {
                        axios.get(this.list_orders_url, {
                            params: this.filter,
                            paramsSerializer: params => queryString.stringify(params)
                        }).then(function (response) {
                            app.orders = response.data;
                        }).catch(function (error) {
                            console.log(error); // todo
                        })
                    },

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

Tips for modifying javascript code to have popups appear as bPopup instead of in a separate popup window

Is there a way to modify the following code so that popup windows open as dpopups instead of just in a new popup window ()? $(document).ready(function() { var table = $('#taulu').DataTable( { "ajax": "taulu.php", "columnDefs" ...

What is the best way to use Rails active storage and VueJS to directly upload files to S3?

I've encountered a challenge in uploading a file to s3 using direct upload s3. My current setup is Rails 5.2 with active storage. However, the Active Storage guide only provides instructions for uploads using built-in rails views. I'm now seeking ...

What could be causing the lack of data to be returned by jQuery.getJSON?

I've come across this method: function getUserName(guid) { var name = "Unknown"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if ...

What steps can I take to ensure that my bot disregards any actions taken by other bots?

I need assistance with configuring my bot to ignore certain actions by other bots and prevent logging them. Below is the snippet of my code: let messagechannel = oldMember.guild.channels.find(r => r.name === config.logsChannel); if (!messagecha ...

Attempting to create a dynamic dropdown menu with animated effects triggered by a key press

I've been attempting to construct a menu that initially appears as a small icon in the corner. Upon pressing a key (currently set to click), the checkbox is activated, initiating the animation. Most of the menu and animation are functional at this po ...

Populate a Textbox Automatically using a Dropdown List

MVC 4 Changing multiple display fields based on DropDownListFor selection Having some issues trying to implement the solution mentioned above. It seems like there might be a problem with either my javascript code or the controller. JavaScript in View ...

Handler for stack trace errors and error handling for promises

Introducing my customized error handling function: function onError(message, source, lineno, colno, error) { sendRequestToSendMail(arguments) } window.onerror = onError In addition to that, I have asynchronous tasks utilizing promises and I aim to captur ...

Ways to merge multiple cells horizontally in a table right from the beginning

Is there a way to start the colspan from the second column (Name)? See image below for reference: https://i.stack.imgur.com/RvX92.png <table width="100%"> <thead style="background-color: lightgray;"> <tr> <td style="width ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

combine the value of one key with the value of another key within an array

const array = [{ id: 1, name: 'Bob', education: [{ degree: 'bachelors', Major: 'computers' }, { degree: 'masters', Major: 'computers' }] }, { id: 2, n ...

Attempting to invoke a promise within a function yields an error message stating that it lacks call signatures

Recently, I came across this interesting class: export class ExponentialBackoffUtils { public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) { function waitFor(milliseconds: number) { return new Pr ...

Getting the local folder name using AngularJs

Is there a way to retrieve the directory name by browsing to a folder and clicking a button? I was considering utilizing <input type="file" /> to achieve this. ...

Having trouble applying styles to a component using forwardRef

I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing. One thing that confuses me is why adding "setState(10);" causes the style of the "Test" ...

I am constantly encountering this issue: Uncaught TypeError - It's impossible to read properties of undefined (specifically 'image') in PromptCard at PromptCard.jsx on line 37

Click here to see the error message This is the code for my components\PromptCard.jsx file: "use client"; import { useState } from "react"; import Image from "next/image"; import { useSession } from "next-auth/reac ...

"Utilize Ajax and PHP to seamlessly upload a PDF file directly into a MYSQL database

I am trying to figure out how to upload a pdf file from user input into my MySQL database. I have provided code that displays a user registration form with the option to upload a PDF file. My goal is to use AJAX to post this data to a PHP script for storag ...

What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a fun ...

Interfacing Contact Form Data from Vue Application to Magento Using API - A Step-by-Step Guide

Introduction A custom vue-component has been implemented on the application, serving as a contact form. This component is imported into the header component and enclosed within a modal container. The primary function of this contact form is to trigger an ...

Quasar V2 is currently trying to close the LeftDrawer when the base is closed, with the option to reopen it using the hamburger

I am in need of help with Quasar as I am very new to coding and the JS/Quasar framework. I am curious to know if it's possible to customize the qdrawer so that when the page is launched, it is closed by default instead of open, and clicking the hambur ...