Error 400: Token Obtain Pair request failed in Django REST with simpleJWT and Vue 3 composition API

I'm encountering an issue with obtaining the refresh and access tokens when sending a form from my Vue app to the Django REST API. CORS has been enabled, and signing up through the REST API page or using Postman doesn't pose any problems. However, when I send a POST request with Vue, I receive a

POST http://127.0.0.1:8000/api/token/ 400 (Bad Request)
error in the console. Additionally, I'd like to know how I can properly store and display the returned refresh and access tokens. Any suggestions?

<template>
  <div>
    auth 1
    <div id="authenticationDiv">
      <form action="" v-on:submit.prevent="loginUser">
        <input type="text" v-model="username" />
        <input type="text" v-model="password" />
        <button @click="loginUser(username, password)">
          login
        </button>
      </form>
    </div>
    <div>
      <div>acess: {{ accessToken }}</div>
      <div>refresh: {{ refreshToken }}</div>
      <button @click="DisplayText(username, password)">+</button>
    </div>
  </div>
</template>

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

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

    const accessToken = ref("");
    const refreshToken = ref("");

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

    async function loginUser(username, password) {
      fetch(TOKEN_URL, {
        method: "POST",
        headers: {
          "Content-type": "application/json",
        },
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      }).then((response) => {

        username = "";
        password = "";

        return response;
      });
    }

    function DisplayText(username, password) {
      console.log(`username:${username}, password:${password}`);
    }

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

Answer №1

  1. Verify your ALLOWED_HOSTS settings:
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

Alternatively, set it to allow any host:

ALLOWED_HOSTS = ['*']
  1. Ensure proper headers are set and catch errors for more information:
fetch(TOKEN_URL, {
  method: "POST",
  headers: {
    "Content-type": "application/json",
    "X-CSRFToken": csrftoken
  },
  body: JSON.stringify({
    username: username,
    password: password
  })
})
  .then(response => {
    console.log(response);
  })
  .catch(function(error) {
    console.log("ERROR", error);
  });  
  1. Inspect the web developer console for insights on the request content and data being sent.

  2. If using DRF with JWT, note that CSRF token may not be required by default.

  3. I personally store tokens in localStorage. For a guide on React Token-Based Authentication with Django, refer to my tutorial here. While the tutorial is specific to React, the process for Vue will be quite similar. Additionally, there's a discussion on storing tokens in localStorage vs HTTP-only cookies towards the end (worth exploring).

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

Tips for including or excluding a series of comma-delimited values from an input

HTML <div class="wrap_temi"> <ul class="list-inline list-unstyled"> <li class="list-inline-item"> <input type="checkbox" value="amici" autocomplete="off"> Amici </li> <li class="lis ...

Refresh the angular list filter by clicking on it

I'm struggling with updating an Angular list after the filter is changed. Below is the HTML code I am using: <li ng-repeat="items in list | filter:filterList" style="list-style-type:none"> {{items}} </li> Additionally, here is the o ...

Utilizing an Immediate-Invoked Function Expression (IIFE) for jQuery in JavaScript

I'm looking at this code snippet that I believe is an Immediately Invoked Function Expression (IIFE). But, I'm confused about the role of (jQuery) and ($). I understand that it involves passing a reference to jQuery into the IIFE, but can someone ...

Is it possible to load HTML content within a Sweet Alert pop-up

Below is the code I am using to call Swal: window.swal({ title: "Checking...", text: "Please wait", imageUrl: "{{ asset('media/photos/loaderspin.gif') }}", showConfirmButton: false, allowOutsideClick: false }); $.ajax({ t ...

Update the formatting of the dates in the dateRangePicker

Utilizing a dateRangePicker, I am receiving dates in the format "mm-dd-yyyy". Below is my HTML code: <input type="text" name="TextDate" value="10/24/1984" /> Here is the script being used: <script> $(function() { $(&apos ...

Stop zombie.js from loading exclusively third-party resources

During a test, I am using zombie.js to load a page from a local express server. However, the page contains a script element that makes a call to Google Analytics. I want to prevent this external script from loading while allowing other local scripts to run ...

What are some ways to utilize an empty array that has been declared in React's initial state?

I am currently in the process of developing an application that displays a collection of various lists. However, I have encountered a roadblock when attempting to access an empty array that I initialized when setting up the initial state. Here is the state ...

Executing Two Distinct JQuery Api Requests

I'm facing a challenge with integrating the data from two different API calls and processing them together. After receiving JSON responses from both calls, I convert them into GeoJSON format. The next step is to combine these geojson objects in anothe ...

Guide to sending JSON data through the Wufoo Entries API

It seems the current documentation is lacking in detailing the proper procedure for submitting forms via Ajax. Although there is The Entries POST API, it specifically discusses xml and lacks an example payload. Upon further investigation, I discovered Wuf ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

extract individual components from the google books api

It has been quite a while since I last dabbled in JavaScript, so I decided to embark on a project creating a "bookcase" to organize the books I have read and those I still want to read. One challenge I encountered was figuring out how to separate the eleme ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

The value of the input field in jQuery is not defined

I am encountering an issue with an error: jQuery input val() is undefined. I have 3 inputs that are all referencing one item. When I add a new row, I can create a new item (3 rows). All of these rows need to be organized in an array to be sent to a PHP f ...

Dealing with Oversized Images in Jcrop: Tips and Tricks

Utilizing Jcrop for cropping images, everything runs smoothly with small images. However, when I attempt to use large images like 2080x2080 or 1600x1600, it takes up the entire screen and cannot be controlled by CSS properties such as width and height in t ...

The Cloudinary setup does not retrieve information from the .env file

I am currently integrating Cloudinary with my node.js project... Unfortunately, I have encountered an issue where cloudinary.config is not able to read data from the .env file. Instead, I am required to input them directly into the code! const cloudinary ...

A React component enclosed within a useCallback function

According to the React docs, to prevent a Child component from re-rendering in certain cases, you need to wrap it in useMemo and pass down functions in useCallback within the Parent component. However, I'm confused about the purpose of this implementa ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

A fresh javascript HTML element does not adhere to the css guidelines

While attempting to dynamically add rows to a table using Javascript and jQuery, I encountered an issue. Here is my code: <script> $(document).ready(function(){ for (i=0; i<myvar.length; i++){ $("#items").after('<tr class="item- ...

The string length is not valid in repeat$1 (VueJS) [Issue resolved: the usage of 'continue' is reserved in JavaScript

I encountered the Error in execution of function repeat$1 when trying to compile a basic VueJS template. This error is causing the compilation process to fail. I'm struggling to identify the issue within the template. Here's the code snippet: ( ...