# Frontend API Call

To call the APIs we just created using Laravel Passport\Laravel Sanctum we need to follow below steps:

Open axios.js file found at resources/js/src/lib/axios.js and replace with below code:

import Vue from 'vue'

// axios
import axios from 'axios'

const axiosIns = axios.create({
  // You can add your headers here
  // ================================
  baseURL: 'https://127.0.0.1:8000/',
  // timeout: 1000,
  // headers: {'X-Custom-Header': 'foobar'}
})

Vue.prototype.$http = axiosIns

export default axiosIns

Note

Make sure to change the baseURL, timeout and headers according to your requirement.

Now, open Register.vue file found at resources/js/src/views/pages/authentication/Register.vue and find below code:

WARNING

starter-kit won't have Register.vue file so do import it from full-version and proceed further.

methods: {
  register() {
    this.$refs.registerForm.validate().then(success => {
      if (success) {
        useJwt.register({
          username: this.username,
          email: this.userEmail,
          password: this.password,
        })
          .then(response => {
            useJwt.setToken(response.data.accessToken)
            useJwt.setRefreshToken(response.data.refreshToken)
            localStorage.setItem('userData', JSON.stringify(response.data.userData))
            this.$ability.update(response.data.userData.ability)
            this.$router.push('/')
          })
          .catch(error => {
            this.$refs.registerForm.setErrors(error.response.data.error)
          })
      }
    })
  },
},

Replace register method with below method which includes the API call.

WARNING

This is just showing how to use axios to make API calls for authentication. Please consider checking below resources for valid API response.

FAQ: How to check what frontend expects in API response

FAQ: I don't have refresh token in my authentication flow

Article: Frontend Authentication Flow

methods: {
  register() {
    this.$refs.registerForm.validate().then(success => {
      if (success) {
        this.$http.post('/api/auth/register', {
          name: this.username,
          email: this.userEmail,
          password: this.password,
          c_password: this.password
        }).then(res => console.log(res))
      }
    })
  },
},

Open your console and you should see following API response

Response

Note

Repeat the same process for Login, get user and logout APIs to authenticate user, get user details and logout the user.

Last Updated: 11/16/2022, 12:36:59 PM