首页 > 解决方案 > 400 Bad request for Token Get Pair, Django REST simpleJWT and Vue 3 composition API

问题描述

在将表单从我的 vue 应用程序发送到 django rest api 时,获取刷新和访问令牌时出现问题。CORS 已启用。通过 rest api 页面注册并使用 postman 不会导致任何问题。当我使用 Vue 发送发布请求时,POST http://127.0.0.1:8000/api/token/ 400 (Bad Request)会在控制台中弹出。+ 我如何存储/显示返回的刷新和访问令牌?有什么建议吗?

<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/";

    // function getCookie(name) {
    //   let cookieValue = null;
    //   if (document.cookie && document.cookie !== "") {
    //     const cookies = document.cookie.split(";");
    //     for (let i = 0; i < cookies.length; i++) {
    //       const cookie = cookies[i].trim();
    //       // Does this cookie string begin with the name we want?
    //       if (cookie.substring(0, name.length + 1) === name + "=") {
    //         cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    //         break;
    //       }
    //     }
    //   }
    //   return cookieValue;
    // }
    // const csrftoken = getCookie("csrftoken");

    async function loginUser(username, password) {
    // var csrftoken = getCookie("csrftoken");
      fetch(TOKEN_URL, {
        method: "POST",
        headers: {
          "Content-type": "application/json",
            // "X-CSRFToken": csrftoken,
        },
        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,
        // csrftoken,
      loginUser,
      accessToken,
      refreshToken,
      DisplayText,
    };
  },
};
</script>

标签: javascriptvue.jsdjango-rest-framework

解决方案


  1. 检查ALLOWED_HOSTS
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

或匹配任何:

ALLOWED_HOSTS = ['*']
  1. 设置标题并捕获错误,也许会有更多信息?
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. 检查 Web 开发人员控制台?您的请求看起来如何?您是否在请求中发送了正确的数据?

  2. 如果您将 DRF 与 JWT 一起使用,则默认情况下不需要 CSRF 令牌。

  3. 我将令牌存储在 localStorage 中。你可以在我的教程中查看关于 React Token-Based Authentication to Django REST API Backend 的详细信息。它适用于 React,但适用于 Vue 将非常相似。在教程的最后,还有关于将令牌存储在 localStorage 中与 cookie httpOnly 的讨论(值得一读)。


推荐阅读