Axios: Actions taken by users prior to logging in

After successfully sending "EnvioLogin" with the correct email/password, I am able to obtain the access token from "/login", but I encounter an issue when trying to access "/users" after that. Upon inspecting in my browser, I found these image links: https://i.sstatic.net/yBJK0.jpg https://i.sstatic.net/bWQEG.jpg

Is there a way for me to execute created hooks after the user logs in?


import axios from "axios";
export default {
  name: "login",

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

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

    console.log(response);
  },

  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");
          this.showLogin = false;
        }
      } catch (error) {
        this.showError = true;
        setTimeout(() => {
          this.showError = false;
        }, 2000);
      }
    },
  },
}

Answer №1

The developers suggest organizing the code within the created hook by creating a separate method called getUsers and then invoking it in the EnvioLogin method:


import axios from "axios";
export default {
  name: "login",


  data() {
    return {
      showError: false,
      email: "",
      password: "",
    };
  },
  created() {
   this.getUsers();
  },

  methods: {
   async getUsers(){
   const response = await axios.get("api/users", {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token")
      }
    });

    console.log(response);
  },
    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") {
         this.getUsers();
          console.log(response);
          this.$router.push("intermediorotas");
          this.showLogin = false;
        }
      } catch (error) {
        this.showError = true;
        setTimeout(() => {
          this.showError = false;
        }, 2000);
      }
    },
  },

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

In Angular, link a freshly loaded ".js" controller to a newly loaded "html" view following the bootstrapping process on ngRoutes

As a newcomer to Angular, I have been experimenting with loading dynamic views using ngRoutes (which is very cool) along with their respective .js controllers for added functionality. However, I am encountering difficulties in binding them together after b ...

Ensuring that the image perfectly fills the entire screen on an iPhone X using React Native

Looking for a solution to make my image fit the entire screen on the iPhone X simulator. I've tried adjusting the imageContainer width to "100%" and the container that encompasses everything, but haven't had any luck. Would appreciate any suggest ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Error: Property 'onclick' cannot be set on a null object

JavaScript isn't my strong suit, so I'm struggling to solve this issue. The console is showing me the following error message: Uncaught TypeError: Cannot set property 'onclick' of null <script> var modal = document.getE ...

Allowing users to submit content in a textarea field by pressing the enter key in

<td> <textarea name="message" id="message" rows="1" style="padding: 10px;margin-left: 12px;border-radius: 10px; margin-right: 0px; width: 430px;"></textarea> <td style="padding-left:0px"> <a title="Send" id="sendB ...

Assistance with Javascript Objects Using JSON and AJAX

Currently, I am utilizing Ajax to retrieve data from my Json file. A problem I am facing is that in one particular div of my html, I need to include both a heading and a paragraph. I attempted to create a property like so: "headingpara": "<h1> blah ...

Creating engaging animations with styled components in ReactJs

I have embarked on the journey of crafting a testimonial section that bears resemblance to the testimonials displayed on the website www.runway.com. Leveraging styled-components, I've made progress in piling up the cards at the center of the screen, w ...

Unable to save the session identifier from the response headers while utilizing sessions in react/frappe framework

I am attempting to retrieve the session id (sid) from the response headers in a unique scenario. My client application is situated on a local environment, while my API is hosted on an ERP Next server. Upon sending a login request from the React app, I am ...

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

Reorganizing objects upon insertion in Mongo DB

I am encountering an issue in my Node.js app where MongoDB is causing objects to be reordered when inserting new records into the database. I am using the following insert method: collection.insert(object, {safe:true}, function(err, result) { if (err) ...

Having trouble with Node JS res.redirect() not functioning as desired?

I'm attempting to use res.redirect() to redirect to an external URL, but the host name isn't being replaced. For example: My current URL: https://example.com Desired redirect URL: When I use res.redirect("https://example-2.com/pqr?par=123 ...

Trouble with Map method not displaying data in Next.js

I am currently working on a Map Method but facing an issue. The data 1,2,3,4,5 is successfully displayed in the console.log, but not showing on the website. import React from 'react' export default function secretStashScreen() { const numbers = ...

Transform the JSON object into a different JSON format

I am in the process of restructuring the JSON data which is currently organized by categories, with each category containing multiple locations. Each location consists of latitude/longitude coordinates and an area code: { "cat1":[ {"location":{ ...

Styling the <Autocomplete/> component in Material UI with React to achieve rounded corners

Google's search bar has always been a favorite of mine, with its rounded corners and generous text padding. https://i.stack.imgur.com/UbKrr.png I'm attempting to replicate this aesthetic using Material UI's <Autocomplete/> component ...

Create numerical arrays using specific algorithms

I am in need of several arrays: array 1 = [1,9,17,25,33,41]; array 2 = [2,10,18,26,34,42]; and so on. Each array should increment by 8 from the previous one. I want to create this dynamically using JavaScript functions. ...

Unable to connect state to props when utilizing combineReducers

I'm currently working on integrating my state with a specific component using Redux. To achieve this, I have implemented two reducers and utilized combineReducers to merge them into a rootReducer before initializing my store. const rootReducer = comb ...

Currently, I am experiencing difficulties with two specific aspects of the website I am working on - the hamburger menu and the slideshow feature

I'm having trouble with the menu on my website. It's not functioning as expected - the dropdown feature isn't working, and two items are not staying in the correct position under the parent ul despite attempts to position them using CSS. Add ...

AngularJS uses two ng-repeat directives to manage and manipulate data in

I'm implementing a feature where I have two views in my HTML5 code that display the same list. <div class="list" data-ng-repeat="item in model.items"> <div class=list-item"> {{ item.name }} <a data-ng-click="addToLi ...

Do not continue submitting if the innerHTML matches the specified value

I am currently working on a web page that verifies if an email entered by the user is available in the database. If it is, I need to prevent the form from being submitted. To achieve this, I have implemented Ajax for real-time checking of the email and di ...