Anticipating the response from the API call and storing it within a variable

When I call the getLogin method within the onSubmit method, I am expecting a code to be returned that I need. However, instead of receiving the expected code, I am getting 0 as output. Can someone help me figure out what I am doing wrong?

<template>
  <div class="container">
    <h1>Main title</h1>
    <form @submit="onSubmit" class="add-form">
      <div class="submit-div">
        <input type="submit" value="Continue" class="btn" />
      </div>
    </form>
  </div>
  <router-view />
</template>
<script>
export default {
  name: "Home",
  components: {},
  data() {
    return {
      responseCode: 0,
      responseData: []
    };
  },
  methods: {
    async onSubmit(e) {
      e.preventDefault();
      this.responseCode = await this.getLogin();
      console.log(this.responseCode);
    },

    async getLogin() {
      var requestOptions = {
        method: "GET",
        redirect: "follow"
      };

      await fetch("http://localhost:5000/api/twikey/login", requestOptions)
        .then(response => response.json())
        .then(data => {
          return data.Authorization;
        })
        .catch(error => console.log("error", error));
    },
  }
};
</script>
<style scoped>
.container {
  width: 70%;
  height: 500px;
  margin: auto;
}
</style>

Answer №1

It is recommended to use either await or .then() on a promise, but not both simultaneously.

To handle form submission, you can utilize the

@submit.prevent="onSubmit"
directive and eliminate the need for e.preventDefault().

<template>
  <div class="container">
    <h1>Main title</h1>
    <form @submit.prevent="onSubmit" class="add-form">
      <div class="submit-div">
        <input type="submit" value="Continue" class="btn" />
      </div>
    </form>
  </div>
</template>

<script lang='ts'>
import { defineComponent } from "vue";
export default defineComponent({
  data() {
    return {
      responseCode: 0,
      responseData: [],
    };
  },
  methods: {
    async onSubmit() {
      this.getLogin()
      .then(r => {
        this.responseCode = r;
        console.log(r)
      });
    },
    getLogin() {
      return fetch("http://localhost:5000/api/twikey/login", {
        method: "GET",
        redirect: "follow",
      })
        .then((r) => r.json())
        .then((r) => r.Authorization);
    },
  },
});
</script>

Answer №2

It is recommended that you proceed with your request by following these steps:

  axios.get('http://localhost:8080' + this.paramId)
            .then((resp)=>{
            this.event = resp.data.data;
            console.log(resp.data.data)
})

Once the request is successful, the response will be saved as "event." This response contains data returned from the backend, including HTTP status code 200. You can view it in the console or use it in your code.

If this event is triggered by an object, you can implement a prevention mechanism within that object. For example, if it is a button:

<button v-on:click.prevent="doFunction();"> Sign-up </button> 

You can then create a function that includes this GET request like so:

methods:{
 doFunction{
       axios.get('http://localhost:8080' + this.paramId)
            .then((resp)=>{
            this.event = resp.data.data;
            console.log(resp.data.data)
})

 }

Please inform me if this solution resolves your issue!

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

Updates to Firebase data do not automatically reflect in Google Charts

I've successfully connected my Firebase to Google Charts, however I am facing an issue in displaying a 'no data' message when there is no data available. Currently, I have set a Firebase data value of 'NA' for a single user, which ...

Creating a custom sorting function in Typescript for arrays using a comparator

Looking to implement a custom sorting method for an array that consistently arrives in varying orders: [{code: 'A'},{code: 'O'},{code: 'I'}], [{code: 'O'},{code: 'A'},{code: 'I'}], ... The desir ...

Obtaining access to an element using jQuery AJAX in MVC

When using jQuery ajax to send data to an action, I want to display the returned data in a table. The action method returns an object in Json format: public JsonResult CountryList(.....) { CountryTypeViewModel obj = new CountryTypeViewModel(); . ...

Fetch routes from an external API using a component and integrate them seamlessly into the router

I want to fetch my routes from an external API, considering that some users may not have the necessary permissions to access a particular module. My navbar makes an API request to retrieve all available modules. These modules contain the file path for the ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

Mismatch of data types in Google Visualization

I am working with Google Visualization and receiving Unix Epoch timestamps that I need to convert into an array of strings for use in Google Charts. However, I keep encountering an error: Type mismatch. Value 2017-8-25 16:23:54,2017-8-25 16:11:54,... does ...

The function was not invoked as expected and instead returned an error stating "this.method is not

I need help with an issue in my index.vue file. The problem lies in the fancy box under the after close where I am trying to call the messageAlert method, but it keeps returning this.messageAlert is not a function Can someone please assist me in resolving ...

What is the best way to initiate a Post/Get Request to NodeJS without causing a page refresh?

Struggling to run a NodeJS function after clicking a button? You're not alone. Ajax requests haven't been working for me either when it comes to running NodeJS functions. I've got a bash script that generates a JSON file which I want to par ...

How can I extract information from an iCal file to display the upcoming event?

Is there a method to extract information from an iCalendar file and display the most recent event using JavaScript or node.js? Your assistance on this matter would be greatly valued. Many thanks ...

Duplicate request submissions in ExtJs causing inefficiency

Trying to resolve an issue with my ExtJs table that handles remote filtering, sorting, and paging of data on the server. The problem arises when a default request is being sent alongside every other request: localhost/request?page=1&start=0&limit= ...

Deciphering the mechanics of collection referencing in mongoose

Today, I am delving into the world of using references in mongoose for the first time. I am trying to figure out how to save a template with a user ID. Do we need to retrieve the createdBy value from the client, or can it be inserted into the templateSchem ...

Text in SVG file misaligned at the edge

After creating an SVG with a base64 background image and two text areas for top and bottom texts, I encountered an issue on Internet Explorer and Edge. The problem is that the bottom text is aligned to the left instead of the center, and its position is in ...

Error encountered when running npm build in Vue.js: Conflict arises in bundle.css due to multiple chunks (app and chunk-f33d301e) emitting assets with the same filename

After uncommenting the CSS extracting method in the vue.config.js file and running a production build, I encountered the error mentioned above. // vue.config.js file // Uncomment before executing 'npm run build' css: { extract: { ...

Exploring Angular's Structural Directive for Parsing HTML Strings

I need help parsing an HTML string with a structural directive inside ng-template. Currently, it is being displayed as a string instead of the desired outcome where the structural directive iterates three times and shows three li elements. How can I achiev ...

Instructions for passing the chosen value to Django

I am struggling to set up a search button using Ajax and Django. I need to send the selected value to the server, but I can't seem to retrieve the value from the select HTML tag. The variable value always ends up empty ({"obj":""}). Any ideas? HTML : ...

Is it better to modify attributes during the ng-repeat cycle or after the cycle ends?

Consider a scenario where a simple directive is defined as follows: app.directive('seo', function() { return { template: '<meta ng-repeat="tag in data" {{tag.attribute}}="{{tag.name}}" content="{{tag.content}}" />', ...

``Enhanced feature allowing users to input different zip codes in a weather

Currently, I am exploring the integration of a weather plugin found at: http://jsfiddle.net/fleeting/a4hbL/light/ The plugin requires either a zipcode or woeid to function. Instead of hardcoding the zipcode, I am looking to make it dynamic so that users f ...

The warning message "UnhandledPromiseRejectionWarning: Error: ENOENT: unable to locate the specified file or directory" was triggered due to the absence of the file "level

Currently, I am working on a project involving a popular application called Discord. My main task is to code a bot that can send images from a local file source. The bot is hosted on Heroku, which means all the files are stored in the cloud and maintained ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

Validation of default values in contact forms

Obtained a free contact form online and hoping it works flawlessly, but struggling with validation for fields like "Full Name" in JS and PHP. Here is the HTML code: <input type="text" name="contactname" id="contactname" class="required" role="inpu ...