I'm confused as to why my Vue 3 Composition API with Django REST JWT setup is executing 2 POST requests even though I'm only sending it once

After successfully sending a POST request with axios to the Django REST API for tokens, I receive a 200 response containing refresh and access tokens that are then stored in local storage. However, upon inspection of the network tab, I noticed there is a second successful POST request being made. Why is this happening when I only submitted the form once?

<template>
  <div>
    auth 1
    <div id="authenticationDiv">
      <form action="" v-on:submit.prevent="loginUser(username, password)">
        <!-- <input type="text" v-model="username" /> -->
        <!-- <input type="text" v-model="password" /> -->
        <button @click="loginUser(username, password)">
          login
        </button>
      </form>
    </div>
    <div></div>
  </div>
</template>

<script>
import { ref } from "vue";
import axios from "axios";

export default {
  setup() {
    const username = ref("aleksisDjango");
    const password = ref("zimbabwe123");

    const ACCESS_TOKEN = "access_token";
    const REFRESH_TOKEN = "refresh_token";

    const TOKEN_URL = "http://127.0.0.1:8000/api/token/";

    const tokenRequest = axios.create({
      baseURL: TOKEN_URL,
      timeout: 5000,
      headers: {
        "Content-Type": "application/json",
        accept: "application/json",
      },
    });

    const loginUser = (username, password) => {
      const loginBody = { username, password };
      return tokenRequest
        .post("http://127.0.0.1:8000/api/token/", loginBody)
        .then((response) => {
          window.localStorage.setItem(ACCESS_TOKEN, response.data.access);
          window.localStorage.setItem(REFRESH_TOKEN, response.data.refresh);
          // console.log(response.data)
          console.log("done");
          // this line is executed twice in the command line
          return Promise.resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
          return Promise.reject(error);
        });
    };

    return {
      username,
      password,
      loginUser,
    };
  },
};
</script>

<style scoped>
#authenticationDiv {
  margin: 20px 50px;
}
</style>

Answer №1

Here is the issue you're facing:

<form action="" v-on:submit.prevent="loginUser(username, password)">
        <!-- <input type="text" v-model="username" /> -->
        <!-- <input type="text" v-model="password" /> -->
        <button @click="loginUser(username, password)">
          login
        </button>
      </form>

The problem occurs because a request is triggered when the button is clicked and another request is sent when the form is submitted. To fix this, you can either:

<form action="" v-on:submit.prevent="loginUser(username, password)">
        <!-- <input type="text" v-model="username" /> -->
        <!-- <input type="text" v-model="password" /> -->
        <button>
          login
        </button>
      </form>

Or

<form action="#">
        <!-- <input type="text" v-model="username" /> -->
        <!-- <input type="text" v-model="password" /> -->
        <button @click="loginUser(username, password)">
          login
        </button>
      </form>

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

Is there a way to detect when the escape key is pressed?

Is there a way to detect when the escape key is pressed in Internet Explorer, Firefox, and Chrome? I have code that works in IE and alerts 27, but in Firefox it alerts 0 $('body').keypress(function(e){ alert(e.which); if(e.which == 27){ ...

Incorrect data retrieval from JSON object with JQUERY

I am working on a function that extracts data from a database on the server-side and assigns it as the value of a textbox on the client-side. The function is functioning correctly on the server-side, but on the client-side, when I use console.log to view t ...

The content in the footer is not displaying correctly (Vuejs)

I recently developed a component with a title and a background color meant to cover the entire page, but it seems to have a top margin that I can't seem to remove. Additionally, I created a footer component that should always stay at the bottom of the ...

The strange interaction between Three.js and web workers

I've been experiencing some unusual behavior with web workers in a three.js application. Initially, everything looks fine when loading a new page. However, after about 20 page reloads, and only when web workers are running, this strange phenomenon oc ...

Techniques to dynamically insert database entries into my table using ajax

After acquiring the necessary information, I find myself faced with an empty table named categorytable. In order for the code below to function properly, I need to populate records in categoryList. What should I include in categoryList to retrieve data fro ...

JavaScript code does not run when a page is being included

On my AngularJS-based page, I have included some additional HTML pages like this: <div data-ng-include src="includehtml"></div> Here is the JavaScript code: $scope.selectImage = function(id) {$scope.includehtml = id;} (I pass the HTML file ...

"By implementing an event listener, we ensure that the same action cannot be

function addEventListenerToElement(element, event, handlerFunction) { if(element.addEventListener) { element.addEventListener(event, function(){ handlerFunction(this.getAttribute("src")); }, false); } } //initialize the function addEve ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

The virtual method 'android.location.Location' was called in error

I'm using WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, options) from MobileFirst to retrieve a device's location. Initially, everything works smoothly as I successfully obtain the location. However, after clearing t ...

Selecting an option from the knockout dropdown menu

I implemented a language dropdown in layout.chtml using knockout js. <select id="Language" class="styled-select" data-bind="value: Language,options: locale, value: selectedLocale, optionsText: 'name'"></select> var viewModel = th ...

Creating customized JavaScript bundles with TypeScript - a beginner's guide

Our ASP.NET MVC application contains a significant amount of JavaScript code. To optimize the amount of unnecessary JS being loaded to the browser, we utilize the BundleConfig.cs file to create multiple bundles. On the View, we implement logic to determin ...

Images in the public/image folder cannot be loaded due to a 403 Forbidden error in Laravel, Vue.js,

Although the image in my profile is displayed perfectly, I have encountered an error in the console. When trying to access the image from the public folder, no error occurs. However, if I attempt to access it from the image folder, which is a subfolder, th ...

Husky and lint-staged failing to run on Windows due to 'command not found' error

I'm facing issues with getting husky and lint-staged to function properly on my Windows 10 system. Here's how my setup looks like: .huskyrc.json { "hooks": { "pre-commit": "lint-staged" } } .lintstagedrc ( ...

Tips for displaying specific data from a sub-array using VueJS

I am facing an issue with a collection of JSON format files structured as follows: { "_id" : "name_id", "apkMode" : "SCROLL", "date" : "2022-04-25", "timestamp" : NumberLong(16551858 ...

The issue of slides overlapping in a Javascript slideshow during auto play mode

I encountered an issue while creating an automatic slideshow with 4 slides. Upon autoplay for the first time, slide 1 overlaps slide 4, as well as slide 2 and 3. This only happens once after the site loads. However, on subsequent playthroughs or when using ...

Retrieve data from specified <td> element in an ASP.NET MVC application

Within my View, I am displaying data using a table. Below is the code snippet: @foreach (var item in Model) { <tr > // Table row content here... </tr> } I have buttons with ...

Struggling to eliminate background color from Bootstrap navigation on top of image slider?

I am currently attempting to make the second navigation bar transparent so that the image behind it is visible. I have tried applying CSS to achieve this transparency: #nav > .navbar-inner { border-width: 0px; -webkit-box-shadow: 0px 0px; box-shadow: 0 ...

The Mongoose framework captures and stores all input parameters from the request body

Currently in the process of setting up a small API, I am handling data validation on the client side of my application. As I go through this process, I am also organizing my data to align with my mongoose schema. My current attempt involves... router.rou ...

Is there a problem with evalJSON() causing Simple AJAX JS to work on Safari locally but fail on the server and in Firefox?

I created a script that utilized Prototype's AJAX methods to fetch Twitter data in JSON format, process it, and display it within a div. The script was functioning perfectly during testing on Safari 4.0.3 on an OS 10.6.1 machine. However, when I uploa ...

Result array, employed as an input for auto-suggest functionality

I’m currently working with an array where I am iterating over an object from an API endpoint that is in stdClass format: foreach($searchResults->hits as $arr){ foreach ($arr as $obj) { $fullType = $obj->_source->categories; print_r($fu ...