The Holy Alliance of Laravel and Vue

I am facing issues with user authentication using Laravel Sanctum. I have set up everything properly, with Vite and Vue 3 as the frontend. The problem arises when I attempt to login with Laravel's default auth - it works fine. However, when I make a request from the Vue frontend like this:

const AxiosInstance = axios.create({
            headers: {
                Accept: "application/json",
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/json",
                "X-Requested-With": "XMLHttpRequest",
            },
            baseURL: "http://127.0.0.1:8000/",
            withCredentials: true,
        });

The actual issue arises when I try to fetch the user data, it always returns Unauthenticated:

const user = async() => {
            await AxiosInstance.get('api/user')
        }

Even though the user is created directly from axios, it remains unauthenticated. I have checked if the user is logged in, and Laravel recognizes it with something like:

        @guest
            <h1>Welcome guest</h1>
        @else
            <h1>Welcome user</h1>
        @endauth

But why is 'api/user' route not authenticated?

Answer №1

The reason behind Laravel Sanctum using Bearer token is for authentication purposes.

To modify your Axios instance, follow these steps:

import axios from "axios";

const token = localStorage.getItem('auth_token')
 const api = axios.create({
    baseURL: 'http://127.0.0.1:8000/api/v1/',
    timeout: 1000,
    headers: {
        'Accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
  });

  export default api

I believe this solution will be beneficial to you.

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

Error encountered during Heroku deployment: "sh: 1: tailwind: not found"

package.json: "devDependencies": { "tailwindcss": "^0.7.4" }, "scripts": { "tailwind:css": "tailwind build src/css/tailwind.src.css -c tailwind.js -o src/css/tailwind.css", "start": "npm run tailwind:css && react-scripts start", ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

Having difficulty implementing two-way binding on SELECT element within Angular JS programmatically

Struggling with implementing two-way binding for SELECT elements. Attempting to dynamically change the selected element through code. While I've come across examples on Stackoverflow for binding the change event for SELECT, finding resources on the ap ...

What is the best way to execute operations on two distinct datasets within a single function using RxJS?

Is there a way to perform operations on two separate data collections within a single function in RxJS, returning an observable instead of void? This function is located within a service and I intend to subscribe to it from my component. I believe some re ...

Choose only one option from the dropdown menu at a time within the specified div

I attempted to utilize the "setSelected" option on my multiselect feature, but I noticed that it does not function with div elements (at least I could not make it work myself). I am endeavoring to create two synchronized multiselects using this example: b ...

How do I access and read a map within an array from Firebase using ReactJS?

I have an array that contains a map with two values: title and content. https://i.stack.imgur.com/WLWVG.png I am trying to read all the values in the array as if it were a map. However, I have attempted this code without success. Can anyone assist me? {d ...

Vue: JSON input ended abruptly while parsing near "...version":"0.5.0","dev"

Currently, I am diving into learning Vue JS with the intention of developing applications using it. To begin with, I went ahead and installed Vue by running the command: npm install vue-cli -g However, a close friend brought to my attention that this met ...

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

Pug does not have access to computed properties within the dynamic class attribute of a Vue component

After attempting to dynamically toggle the className based on computed property and encountering issues in Pug, I found that manually setting 'true' to a className was the solution. Even after trying to reassign the computed property to a Pug var ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

When attempting to use Arabic characters in my PDF file with LIP, I encounter an error: "TypeError: font must be of type PDFFont or n, but was actually of type NaN"

all I am facing an issue with Arabic characters when trying to use different fonts in my project. I have attempted to encode the Arabic letters using various npm packages, but I keep receiving a TypeError: font must be of type PDFFont or n but was actuall ...

Is it feasible to package shared modules into individual files using Browserify?

In my web app, I am using Browserify, Babel, and Gulp to bundle my scripts into a single file. However, when I checked the file size, it was over 3MB which seems excessive to me. Although I'm not entirely sure how Babel and Browserify modify my sourc ...

Identifying the [__ob__: Observer] in Vue: A Beginner's Guide

When I work with my component, I iterate over a data property that holds an object to verify if any values have been set. One of the values within this object is an array. However, when the array is empty and I attempt to log its value, the console shows: ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Concealing Vimeo's controls and substituting them with a play/pause toggle button

I'm currently working on implementing the techniques demonstrated in this tutorial (), but unfortunately the code in the fiddle I put together doesn't appear to be functioning correctly. I'm at a loss as to what might be causing this issue. ...

The property or method 'assign' is not supported in the Vue.js object

Upon loading the site on IE 11, a blank page is displayed I attempted to resolve the issue by including "@babel/polyfill" but unfortunately, it did not work In my package.json file: "dependencies": { "@babel/polyfill": "^7.4.4", "axios": "^0.18 ...

JSFiddle Functioning Properly, But Documents Are Not Loading

My JSFiddle is functioning properly, but the files on my computer aren't. It seems like there might be an issue with how they are linking up or something that I may have overlooked. I've checked the console for errors, but nothing is popping up. ...

The port has not been defined

My Node server appears to be operational, however the console is displaying an error message stating that the port is undefined. const express = require('express'); const env = require('dotenv') const app = express(); env.config(); ap ...

Leverage Angular's constant feature in scenarios that extend beyond the

Even though it may not be recommended, I find it fascinating to use Angular services outside of the angular framework. One example is having .constant('APIprefix','/api') I am curious about how to access the value of APIprefix outside ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...