Guide to utilizing axios.request(config) in Vue.js

I have been attempting to use Axios in my vue.js project to make HTTP requests. Despite reviewing the Axios documentation on GitHub and exploring various examples online, I have yet to find a solution. My goal is to create a configuration file where I can store request paths and then utilize Axios to call them. With numerous APIs that need to be accessed, I believe keeping them in a separate file would be more efficient. Rather than using axios.get or axios.post, I would prefer to implement the following structure:

// within my APIs file 
export default {
  GetAll: {
    method: 'get',
    url: '/Book/GetAll'
  },
  GetById: {
    method: 'GET',
    url: 'Book/GetById/{id}'
  },
  Add: {
    method: 'POST',
    url: 'Book/Add'
  }
}
// Axios instantiation 
import Axios from 'axios'

Vue.use({
  Axios
})

const Server = Axios.create({
  baseURL: myUrl
})

export default Server

// within my component

import Server from './server'
import Api from './api'

export default {
  async mounted() {
    var list = (await Server.request(Api.GetAll)).data

    var book = (await Server.request(Api.GetById)).data
  }
}

While I am able to retrieve the list in the component, I am unsure how to properly call the GetById API.

Answer №1

If you want to improve your REST API calls, consider structuring them like this:

class ApiHandler {
    constructor() {
        this.client = axios.create({
            baseURL: 'your-base-url-here'
        });
    }

    async get(url, params = {}) {
        return this.client.request({
            method: 'get',
            url: url,
            params: params
        })
    }

    async post(url, data = {}) {
        return this.client.request({
            method: 'post',
            url: url,
            data: data
        })
    }

    async getById(id) {
        return this.get(`Book/GetById/${id}`)
    }
}

const handler = new ApiHandler();
const result = await api.getById(1);

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

Determining the selected option's value made by the user

On my index.php file, which contains the form and function, I have the following code: $(function() { $.ajax({ type: "POST", url: "invtype.php", data: "getrevenuetype=true", success: function(b){ $("#revenue ...

Accessing Wikipedia's API in order to retrieve search query results

I'm currently working on incorporating Wikipedia's API into my web page to execute a search query and display the results. Here is the progress I've made so far: "use strict"; $(document).ready(function(){ function searchWikipedia(searchC ...

Is there a way to apply styles to a checkbox's child element depending on the checkbox's state without relying on ternary operators within Styled Components?

I am currently working on styling this component using Styled Components, but I feel like my current approach is a bit of a hack. What would be the best practice for incorporating Styled Components to style this component effectively? If I were to use Pla ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

Tips for restricting users from inputting spaces into a form field using ReactJS

Within my application, I have developed a specialized component named QueryForm that serves the purpose of enabling search capabilities. The code snippet being outputted by this component is as follows: ...

Arrange the given data either by ID or Name and present it

Here is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <style> .content{ border: 1px solid gray; width: 250px; ...

Seeking a way to keep the returned Ajax string consistent and prevent it from fading away after page transition

I have a form that appears when the user clicks on the "Edit" link, allowing them to input their profile information. Upon submission, the data is processed via Ajax and saved in an SQL database using a PHP script. After saving the new profile, I would lik ...

Is it recommended to add the identical library to multiple iFrames?

Here's a quick question I have. So, my JSP page has 4 different iFrames and I've included JQuery UI libraries in it: <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://c ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

How to retrieve nested menu items within the scope by utilizing JSON and AngularJS

I have recently started working with angular and am facing difficulty in accessing the submenu items within my angular application. While I can successfully access the top level menu items, I am struggling to retrieve the second level items. Here is a sni ...

if else statement fails to work in ajax-based login form

I tried to create the code below by referencing processes.php, submit form, and ajax from various sources on the internet. However, my code doesn't seem to be working properly. proccess.php <?php session_start(); ini_set('display_errors&apos ...

Vanilla JS Rock, Paper, Scissors Game - Fails to reset classes upon restarting

Many questions have been raised about this particular topic, but a solution for vanilla js seems elusive. Let's delve into a new challenge: Rock paper scissors with vanilla js. The game functions properly on its own, but the issue arises when attemp ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...

Arrange the data in the table to ensure that it is organized neatly into the appropriate columns

I am currently working on a project that involves creating a table to display user answers for purchased tickets under the corresponding questions. If a question has not been answered, I want to show a dash symbol instead. However, I am encountering an is ...

Error when publishing with npm: Authorization required for this machine. Please authenticate using npm adduser command

After upgrading to node v18 and npm v9, I am attempting to execute npm publish on a package. Unfortunately, I encounter the following error: To proceed, you must be logged in to . You are required to authorize this machine by using npm adduser. This is m ...

odd appearance when objects make contact with one another

I am encountering a peculiar issue with my threejs objects in a scene. Whenever they get near each other or touch, I notice strange triangular artifacts forming at the borders of the objects, as shown in the image below. The renderer being used is THREE.W ...

The Vuex state keeps acting mysterious by claiming to be undefined

Here is my post.js located in src > store > post.js: import Vuex from 'vuex' import Vue from 'vue' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { testState: 'Hello&apo ...

What is the best way to iterate through an array and make use of index values while removing any empty elements along the

In my current setup, I have defined two arrays keyVals and rows: keyVals = [ "Status", "ErrorHeading", "ErrorDetail" ] rows = [ { "Hostname": "ABC", "name& ...

The Jquery .each() method is causing the return value to be undefined

Why is the getColorOptionSelect() function returning an undefined value, even though it has a value when checked with the debugger? I am certain that this issue is related to scope - my apologies for my lack of knowledge in JavaScript. jQuery(document).r ...