Optimizing Backend Access with Laravel and Vue JS: How to Choose the Most Effective Approach

Currently, I am utilizing Laravel API passport to handle authentication in my Single Page Application (SPA) built with Vue. At the moment, whenever I need to access the backend server, I have to include a header in order to be allowed through the protected routes.

// Retrieve user object from local storage
const userObj = JSON.parse(window.localStorage.getItem('token'));
// Constructing the necessary headers for authorization
var header = {
    'Accept' : 'application/json',
    'Authorization' : 'Bearer '+ userObj.access_token
}
// Making a GET request to a protected route
axios.get('/prod/test',{headers : header})
    .then(response=>{
        console.log(response);
    });
}

I was wondering if there is a more streamlined and cleaner approach to achieve this. Thank you.

Answer №1

If you want to set default values for axios, check out this link: https://github.com/axios/axios#global-axios-defaults

axios.defaults.headers.common['Accept'] = 'application/json'
axios.defaults.headers.common['Authorization'] = 'Bearer '+ userObj.access_token;

In Laravel, there is a file called bootstrap.js that comes pre-configured and can be customized to your needs.

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 implementing Header Authorization on a POST FORM with JS/AJAX/JQUERY

Looking to gather user inputs through a form on my webpage and send those values to a PHP hosted on an external site. The Request maker extension indicates that the Header Authorization is included along with other inputs when data is submitted to the exte ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Guide on NodeJS: Harnessing the power of nested functions to ensure synchronous execution

Imagine two functions, A and B, both interacting with a MySQL database using connection.query(...) methods. Function A utilizes a while loop to navigate through the response it receives. Subsequently, function B is invoked with the response from function ...

The requested external js scripts could not be found and resulted in a net::ERR_ABORTED 404 error

import express, { Express, Request, Response } from 'express'; const path = require("path"); import dotenv from 'dotenv'; dotenv.config(); const PORT = process.env.PORT || 5000; const app = express(); app.use(express.static(path.join ...

Error: Trying to destructure a non-iterable object with useContext in React is not valid

ERROR [TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.] Using UserContext : import React, { useContext, useEffect, useLayoutEffect, useState } from "reac ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...

Guide on Declaring an Array in a Node Module and Another JavaScript File (Mongodb)

As a beginner in node.js and programming, I am on a journey to understand how to retrieve a variable's value from Mongodb. Within my app.js file, I have the 'data' variable set up. var data = require("./public/assets/js/data.js"); app.get(& ...

Retrieve the component instance from a Vue watcher

I'm currently developing a project that acts as a bill manager and I am looking to have the subtotal recalculated automatically whenever the quantity or unit value changes. I've tried using watchers and computed properties to achieve this but hav ...

Creating a tree array in JavaScript from JSON data

I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result. [{ "code": "2", "name": "PENDING" },{ "code": "2.2", ...

Is the second parameter of the function being used as a condition?

Why is it necessary to validate the helpText argument within the function to be non-equative to null when its ID is linked with the span tag? The functions task is to set and clear help messages in the form field using built-in CSS classes. <input id ...

Adjust the size of the div to fit its content while maintaining the transition animation

I am aiming for the DIV height to automatically adjust to the text within it, while also maintaining a minimum height. However, when the user hovers their mouse over the DIV, I want the height to change smoothly without losing the transition effect. When ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

The PHP script is not receiving any data when checking if the value is set in the $_POST variable

I'm attempting to transmit values from a JavaScript file using POST method to a PHP page. Here is the AJAX code: let userInput = $input.val(); $.ajax({url: "../checkout/test.php", type : 'post', data : {'userInput': user ...

Encountering a 400 error while trying to implement file upload feature in Spring AngularJS -

Whenever I attempt to upload a file using Spring and AngularJS, I keep encountering the dreaded 400 Bad Request error: > error: "Bad Request" > exception: "org.springframework.web.multipart.support.MissingServletRequestPartException" > message: " ...

What is the best way to fetch data for each specific ID using axios.post when making a URL call?

Utilizing Axios to fetch data from an API and display them as cards in a movie component, I am facing the challenge of enabling users to click on a single movie card and navigate to another page (singlepage.vue) with the corresponding movie ID from the API ...

Button disabled is not functioning properly

Does anyone know why my button is not being disabled when I am not typing in the textbox? Here is the code snippet: $(document).ready(function () { loadData(); function loadData(is_category) { $(document).on('click&apo ...

What is the process for retrieving data through a server-side API request?

I have been working on setting up my API URL in my Node.js backend application. I initially passed the entire URL in my frontend AJAX call, but now I want to transition to a server-side API call to avoid exposing the URL. Since I am not very experienced wi ...

Tips for sending a state into the gtm.js function?

As an intern at a startup, I am the sole front-end developer responsible for coding a website in Next.js. My boss has requested that I incorporate Google Tag Manager into the project. Following the example provided by Next on their GitHub page, I have succ ...

Which is better: specifying a name in window.open() or using replace?

If the current window is www.myparent.com and a button labeled "a" is clicked, it triggers the following function window.open('children','same','',??). Subsequently, a new page will open as www.myparent.com/children. On the o ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...