Integrate Vue Login Functionality using Axios HTTP Requests

Hello everyone! I am new to Vue and currently struggling with making an HTTP Request to my backend. When I check the browser console, I can see the access token retrieved from /login endpoint but when I try to fetch data from api/users, it returns "Token is Invalid". Can someone guide me on how to successfully retrieve my api/users data?

import axios from "axios";
export default {
  name: "login",
  async created() {
    const response = await axios.get("api/users", {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token")
      }
    });

    console.log(response);
  },

  data() {
    return {
      showError: false,
      email: "",
      password: "",
    };
  },

  methods: {
    async EnvioLogin() {
      try {
        const response = await axios.post("api/auth/login", {
          email: this.email,
          password: this.password,
        });
        localStorage.setItem("token", response.data.token);
        const status = JSON.parse(response.status);
        if (status == "200") {
          console.log(response);
          this.$router.push("intermediorotas");
        }
      } catch (error) {
        this.showError = true;
        setTimeout(() => {
          this.showError = false;
        }, 3000);
      }
    },
  },

Answer №1

If you're looking to establish a connection with the backend using a service, it seems like the issue lies in the URL http://localhots:3000/api. It appears that you may have missed out on including the full URL, which should be http://localhost:3000.

import axios from 'axios'
const client = axios.create({
  baseURL: 'http://localhots:3000/api',
  headers: {
    'Content-Type': 'application/json',
  },
})
export default client

After defining the service, remember to import it into your code:

import myService from './myService'
await myService.get(`/auth/login`, {})

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

Best practice for setting up components in Angular 2 using HTML

I have developed a component that relies on external parameters to determine its properties: import { Component, Input } from '@angular/core'; import { NavController } from 'ionic-angular'; /* Info card for displaying informatio ...

The variable ReactFauxDOM has not been declared

Exploring the combination of D3 and React components. Utilizing OliverCaldwell's Faux-DOM element has led me to encounter a frustrating error message stating "ReactFauxDOM is not defined”. Despite following the npm install process correctly... It s ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

Fetching data from local JSON file is being initiated twice

I need some help understanding why my code is downloading two copies of a locally generated JSON file. Here is the code snippet in question: function downloadJson(data, name) { let dataStr = 'data:text/json;charset=utf-8,' + encodeURICompo ...

Robotic Arm in Motion

GOAL: The aim of the code below is to create a robotic arm that consists of three layers (upper, lower, and middle), all connected to the base. There are four sliders provided to independently move each part except for the base which moves the entire arm. ...

Passing an array from the PHP View to a JavaScript function and plotting it

Greetings, I am currently facing the following tasks: Retrieving data from a database and saving it to an array (CHECK) Sending the array from Controller to View (CHECK) Passing that array to a JavaScript function using json_encode (CHECK) Plotting the ...

Change the state of images to the response from the Flickr API

I’m currently developing a similar platform to Flickr, where a GET request using axios is made to fetch photos as the user types in the input field. However, I am facing an issue with my current path returning undefined. Could someone please guide me on ...

In order to ensure functionality on Firefox 3 and Opera, it is essential to include multiple <script> tags and the <!-- //required for FF3 and

I have utilized Spring Roo to create a basic web project. The user interface is JSP-based with a Tiles layout. Upon examining the default layout code, I noticed that the script tags were defined as: <script src="${dojo_url}" type="text/javascript" > ...

Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50. angular.forEach(result1, function (value, key) { $scope.percentage ...

The v-img component in Nuxt.js Vuetify does not seem to be creating the image tag

I'm encountering an issue with vuetify. Instead of generating an "img" tag, it is creating a "div" tag with the background image set to the image path. <v-img v-if="index === 0" :key="index" :alt="ticket.n ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Guide on restricting the character count and displaying the leftover characters using PHP with Ajax

I've been working on implementing a feature to display the remaining characters in a PHP AJAX call. I was successful using JavaScript, but I'm having trouble doing it with AJAX in PHP. Can someone provide assistance? <script type="text/javasc ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Creating specific CSS classes for individual slides in a basic slider framework

So, I have a rather simple slider that is created using only CSS. Each slide has unique labels for navigation buttons. The main question here is: how can I dynamically add or remove classes to specific items on the slide only when that particular slide is ...

What methods can I use to retrieve traversed objects using riak-js?

Utilizing Node with riak-js to interact with a Riak database. I have established two buckets named invites and events. The invites bucket contains a link to events. Is there a way to fetch both the invite object and the corresponding event object in one qu ...

What steps should I take to prevent the appearance of the "Attribute v-b-modal is not permitted here" alert in Intellij IDEA?

Currently, in my Vue.js project I am learning how to use Modals from BootstrapVue. The specific file where I have implemented this is Items.vue, which contains the following snippet: <div v-b-modal="'modal-' + query.id"> // this is lin ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

When a HTML table is generated from imported XML, DataTables will be applied

I am facing a challenge with my code and would appreciate some help. I am trying to load an XML file using jQuery and then use DataTables on my HTML table. However, the plugin doesn't seem to be functioning correctly. When I manually create an HTML ta ...

Adjusting the color of a value in justGage requires a few simple steps to

Is it possible to modify the color and design of the text in the Value parameter of justGage after creating the gauge? My goal is to change the text color to blue with an underline to give it a link-like appearance. Appreciate your assistance. ...