`How to make API calls using axios in a Vue Js application`

I'm attempting to initiate a query search using a URL format like the following:

http://localhost/Stellar/public/api/companies?column=name&direction=desc&page=1

When working with Vue Js 2.0, I am trying to make a call similar to this:

axios.get('$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)')

However, it is generating something along the lines of:

http://localhost/Stellar/public/$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)

The data is not being converted as expected. Any assistance on this matter would be greatly appreciated.

Thank you.

Answer №1

It's important to avoid hardcoding variables into a string, always reference them instead.

Try this approach:

let source = this.source;
let column = this.query.column;
let direction = this.query.direction;
let page = this.query.page;

axios.get(source+"?column="+column+"&direction="+direction+"&page="+page);

Answer №2

To properly format your string, you will need to utilize string interpolation. The process involves enclosing the string within backticks and inserting variables using ${} notation. Here is an example:

let animal = 'cat';

let sentence = `I love my ${animal}. It's a great pet.`;

console.log(sentence);

In your specific case, you should modify your code snippet as follows:

axios.get(`${$(this.source)}?column=${$(this.query.column)}&direction=${$(this.query.direction)}&page=${$(this.query.page)}`);

Note that I also removed the '$' sign before 'page=' assuming it was an error. If it was intentional, please make a mental note of this change.

Additionally, considering your use of $(this.query), etc., I presume you are utilizing jQuery. Alternatively, if you are trying to implement string interpolation incorrectly, be sure to replace the parenthesis with curly braces {} instead.

Answer №3

To begin, it's important to construct the string before making your axios call. When placing variables within a string (the initial parameter of your axios call) in javascript, those variables will not be evaluated.

const url = this.baseURL+'?param='+this.query.param+'&filter='+this.query.filter+'&page='+this.query.page;

axios.get(url).then(response=>{
  console.log(response.data);
});

For more information, refer to: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String

Answer №4

Enhancing your code using the Axios Request Config:

let website = "mywebsite.com";
let settings = {
   parameters: {
       row: 26,
       orientation: 'right'
    }
}
return axios.get(website, settings)
   .then((result) => { 
        ...

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

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

Discovering the maximum value and fetching it from an array

Can you help me identify the array element with the highest 'conversion' value? var barTextData = [ { term: "Roof", clicks: 11235, conversion: 3.12 }, { term: "Snow", clicks: 6309, conversion: 4.45 }, { term: "Chains" ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

Unable to attach child component to reference

I am currently facing an issue with VuePaginator. Despite following the documentation, I am unable to mount it to my Vue app's $refs properties. The pagination feature is working correctly, but I cannot trigger the fetchData() function from my Vue cod ...

Protecting a javascript string in php: A comprehensive guide

Having trouble with my PHP javascript string. Attempted to add a string to a variable within a switch statement but encountered an error: $blocPub = '<script type="text/javascript"> var rdads=new String(Math.random()).substring (2, 11 ...

Seeking further clarification on the topic of `custom Directive` in AngularJS

Implementing a login form in my application, I have chosen to display errors on blur of the input element. Although this approach works, I have encountered several questions regarding a custom directive I created without thorough explanation from the tuto ...

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

How should I properly initialize my numeric variable in Vue.js 3?

Encountering an issue with Vue 3 where the error message reads: Type 'null' is not assignable to type 'number'. The problematic code snippet looks like this: interface ComponentState { heroSelected: number; } export default define ...

Is there a way to eliminate all Unicode characters from a string while preserving specific languages like Japanese, Greek, Hindi, and others?

Is there a way to eliminate all Unicode characters from this text【Hello!】★ ああああ I want to get rid of any unusual symbols (【, ★, 】) while retaining "Hello!" and "ああああ". It should work for all languages, not just Japanese. ...

Learn the process of connecting checkboxes to a database in MeanStack using Angular

Hey everyone, I'm currently working with AngularJS ng-repeat and I am trying to dynamically bind a checkbox based on a true or false value from the database. However, even when the database value is set to true, the checkbox does not automatically che ...

Transferring PointLight Parameters to a Custom Shader using three.js

I am looking to achieve a similar effect as the undulating sphere demonstrated in the Aerotwist Tutorial. Instead of using a fake GLSL hard-coded light like in the tutorial, I am interested in passing information from a three.js PointLight instance to my s ...

Evolution of Vue lifecycle in Vue2

I am currently in the process of migrating from Vue2 to Vue3. To ensure a smooth transition, I want to make changes that Vue2 can handle before moving on to Vue3. Here are the updates in Vue3 lifecycle: https://i.sstatic.net/x1C76.png My plan is to imple ...

Implementing a parallax scroll effect using CSS and dynamically updating the background-position value with JavaScript

How can different Y position percentages be dynamically assigned to multiple layered background images in CSS using JavaScript so that they update as the page scrolls? <style> body { background-image: url(img/bg-pattern-01.png), ur ...

Issues with JQuery .on() occur when functions are passed as arguments

There seems to be a difference in how the .on() function behaves when passing functions as parameters. Interestingly, defining the function inside the parameters versus passing it separately can have different results. An example of this discrepancy is de ...

"Troubleshooting: Issue with the custom rule 'isBetween' validation in Vee validate

I am working on validating text fields and attempting to create multiple rules such as required, minlength, maxLength, and chaining them together. Depending on which parameter is passed, the validation should be performed. While working on this, I referre ...

Is it possible to organize words with HTML elements utilizing JavaScript?

Code is not properly sorting the elements var element='<p><strike>Mango</strike></p>/n<p><em>Orange</em></p>/n<h1>Apple</h1>/n<p><strong>banana</strong></p>/n<p& ...

Is there a way to modify the maximum size limit for a POST request package?

I am encountering an issue while attempting to send an array of bytes using a POST request. In my server-side implementation, I am utilizing Node.js and Express.js. Unfortunately, I am receiving error code 413 or the page becomes unresponsive ('Payloa ...

The Chrome Extension was denied from loading due to a violation of the specified Content Security Policy

I am encountering an issue while loading a Chrome Extension using React. Whenever I try to load it, the error message below pops up: Refused to load the script 'https://code.jquery.com/jquery-3.2.1.slim.min.js' because it violates the following ...

Discover the best method for incorporating Vuetify search functionality within a datatable, especially when the column data is in array

I am dealing with a Vuetify data table component that displays an array of items. Within this array, there is another array that I iterate over using a template tag to display the information in just one column. Take a look at the code snippet below: <v ...