USING AXIOS IN VUE 3

Axios is a popular JavaScript library for making HTTP requests from web browsers or Node.js. It provides a simple and easy-to-use interface for sending asynchronous HTTP requests to REST APIs or other web services.

Prerequisites

Before you get started, ensure that you have the following prerequisites installed on your system:

  • Node.js: You'll need Node.js and npm (Node Package Manager) installed.

Important

The following is the required client library that needed to be installed:

npm install axios

npm registry will find the latest version of the Axios library then download Axios and its dependencies (if any) to project's node_modules directory.

Import Axios in Vue Component

In the beginning of script section of Vue component, import the Axios :

import axios from 'axios';

Now we can use Axios to make HTTP requests

Example: Login Page make a GET request to an API and save the returned token

Step 1: Set up Login Page form in

  <div>
    <h1>Login</h1>
    <form @submit.prevent="login">
      <label for="username">Username:</label>
      <input type="text" id="username" v-model="username" required>
      <br>
      <label for="password">Password:</label>
      <input type="password" id="password" v-model="password" required>
      <br>
      <button type="submit">Login</button>
    </form>
  </div>

Step 2 : Make GET request with using the username and password

import axios from 'axios';
export default {
  data() {
    return {
      username: '',
      password: '',
      returnToken: null,
    };
  },
  methods: {
    async login() {
      try {
          // Make the HTTP request to the API
          const response = await axios.get(
            'Authentication URL',  // example : http://xxxx/xx
            {
              params: {
                username: this.username,
                password: this.password,
              }
            }
          );
          // Check if the response status is OK (200)
          if (response.status === 200) {
            // Assuming the response body contains a JSON object with a 'token' field
            const token = response.data.token;
            this.returnToken = token;
          } else {
            console.error('Failed to retrieve token');
          }
        } catch (error) {
          console.error('An error occurred:', error);
        }
    },
  },
};

Official Documentation Website

Last updated