Javascript 在Vue3 Composition API、DRF中的有效刷新和访问令牌响应上显示登录用户

Javascript 在Vue3 Composition API、DRF中的有效刷新和访问令牌响应上显示登录用户,javascript,django-rest-framework,axios,Javascript,Django Rest Framework,Axios,因此,在成功登录尝试后,我希望vue显示登录的用户名和用户的其他信息。一旦执行了登录用户功能,该怎么做?我应该将提交的用户名分配给新的ref(),还是使用输入ref来显示它?+如果提交的密码或用户名不正确,如何向用户显示错误 <template> <div id="authenticationComponent"> auth 2 <div id="authenticationDiv">

因此,在成功登录尝试后,我希望vue显示登录的用户名和用户的其他信息。一旦执行了
登录用户
功能,该怎么做?我应该将提交的用户名分配给新的ref(),还是使用输入ref来显示它?+如果提交的密码或用户名不正确,如何向用户显示错误

<template>
  <div id="authenticationComponent">
    auth 2

    <div id="authenticationDiv">
      <form action="" v-on:submit.prevent="loginUser(username, password)">
        <div>
          <input type="text" v-model="username" />
          <input type="text" v-model="password" />
        </div>
        <br />
        <button>login</button>
      </form>
      <form action="" v-on:submit.prevent="logoutUser()">
        <button>logout</button>
      </form>

      <form action="" v-on:submit.prevent="refreshToken()">
        <button>refresh</button>
      </form>
    </div>
    <div id="loginInfo">
      logged in as: {{loggedInUser}}
      <!-- how do i display the username, if the password and username is valid? -->
    </div>

    <!--  -->
    <hr />

    <div>
      <button @click="getTodos()">getTodos</button>
    </div>

    <div class="TodoContainer">
      <div v-for="todo in todos" v-bind:key="todo.id" class="TodoComponent">
        <div>{{ todo.todo }}</div>
      </div>
    </div>
    <hr />
    <!--  -->
  </div>
</template>

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

export default {
  setup() {
    // TODO GET REQUEST
    const todos = ref([]);
    const API_URL = "http://127.0.0.1:8000/api/todo-list/";

    // async function getTodos() {
    //   const response = await fetch(API_URL);
    //   const json = await response.json();
    //   todos.value = json;
    // }

    async function getTodos() {
      const response = await fetch(API_URL, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${window.localStorage.getItem(ACCESS_TOKEN)}`,
          "Content-Type": "application/json",
        },
      });
      const json = await response.json();
      todos.value = json;
    }

    // LOGIN THINGS
    const username = ref("");
    const password = ref("");

    const loggedInUser = ref("");

    const ACCESS_TOKEN = "access_token";
    const REFRESH_TOKEN = "refresh_token";
    const TOKEN_URL = "http://127.0.0.1:8000/api/token/";
    const TOKEN_REFRESH_URL = "http://127.0.0.1:8000/api/token/refresh/";
    const BASE_URL = "http://localhost:8000";

    //
    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("login done");
          
          return Promise.resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
          return Promise.reject(error);
        });

    };

    //
    const authRequest = axios.create({
      baseURL: BASE_URL,
      timeout: 5000,
      headers: {
        Authorization: `Bearer ${window.localStorage.getItem(ACCESS_TOKEN)}`,
        "Content-Type": "application/json",
      },
    });

    // LOGOUT
    const logoutUser = () => {
      window.localStorage.removeItem(ACCESS_TOKEN);
      window.localStorage.removeItem(REFRESH_TOKEN);
      authRequest.defaults.headers.Authorization = "";
      console.log("log out");
    };

    // REFRESH
    const refreshToken = () => {
      const refreshBody = {
        refresh: window.localStorage.getItem(REFRESH_TOKEN),
      };
      return tokenRequest
        .post(TOKEN_REFRESH_URL, refreshBody)
        .then((response) => {
          window.localStorage.setItem(ACCESS_TOKEN, response.data.access);
          return Promise.resolve(response.data);
        })
        .catch((error) => Promise.reject(error));
    };

    return {
      username,
      password,
      loginUser,
      logoutUser,
      refreshToken,

      getTodos,
      todos,

      loggedInUser,
    };
  },
};
</script>

<style scoped>
#authenticationDiv {
  margin: 20px 20px;
  text-align: center;
}

#authenticationDiv form {
  display: inline;
}

#authenticationDiv button {
  margin: 0px 20px;
  padding: 0px 18px;
  background-color: white;
  border: 2px firebrick solid;
  color: firebrick;
  transition: 0.3s;
  /* fades in when hover */
}

#authenticationDiv button:hover {
  background-color: firebrick;
  color: rgb(255, 255, 255);
}

#loginInfo {
  margin: 10px 20px;
  padding: 5px 10px;
  background-color: rgba(237, 1, 1, 0.467);
  color: white;
}
</style>

认证2

登录 注销 刷新 以以下身份登录:{{loggedInUser}
盖托斯 {{todo.todo}}
从“vue”导入{ref}; 从“axios”导入axios; 导出默认值{ 设置(){ //TODO GET请求 常数todos=ref([]); 常量API_URL=”http://127.0.0.1:8000/api/todo-列表/“; //异步函数getTodos(){ //const response=wait fetch(API_URL); //const json=await response.json(); //todos.value=json; // } 异步函数getTodos(){ const response=wait fetch(API_URL{ 方法:“获取”, 标题:{ 授权:`Bearer${window.localStorage.getItem(访问令牌)}`, “内容类型”:“应用程序/json”, }, }); const json=await response.json(); todos.value=json; } //登录物品 const username=ref(“”); const password=ref(“”); 常量loggedInUser=ref(“”); const ACCESS_TOKEN=“ACCESS_TOKEN”; const REFRESH\u TOKEN=“REFRESH\u TOKEN”; const TOKEN_URL=”http://127.0.0.1:8000/api/token/"; 常量标记\u刷新\u URL=”http://127.0.0.1:8000/api/token/refresh/"; const BASE_URL=”http://localhost:8000"; // const tokenRequest=axios.create({ baseURL:TOKEN_URL, 超时:5000, 标题:{ “内容类型”:“应用程序/json”, 接受:“应用程序/json”, }, }); 常量登录用户=(用户名、密码)=>{ const loginBody={username,password}; 返回令牌请求 .post(“http://127.0.0.1:8000/api/token/“,登录体) 。然后((响应)=>{ window.localStorage.setItem(ACCESS\u令牌、response.data.ACCESS); window.localStorage.setItem(REFRESH\u令牌、response.data.REFRESH); //console.log(response.data) console.log(“登录完成”); 返回Promise.resolve(response.data); }) .catch((错误)=>{ console.log(错误); 返回承诺。拒绝(错误); }); }; // const authRequest=axios.create({ baseURL:BASE_URL, 超时:5000, 标题:{ 授权:`Bearer${window.localStorage.getItem(访问令牌)}`, “内容类型”:“应用程序/json”, }, }); //注销 const logoutUser=()=>{ window.localStorage.removietem(访问令牌); window.localStorage.removietem(刷新令牌); authRequest.defaults.headers.Authorization=“”; 控制台日志(“注销”); }; //刷新 常量刷新令牌=()=>{ 常数刷新体={ 刷新:window.localStorage.getItem(刷新令牌), }; 返回令牌请求 .post(令牌\刷新\ URL,刷新正文) 。然后((响应)=>{ window.localStorage.setItem(ACCESS\u令牌、response.data.ACCESS); 返回Promise.resolve(response.data); }) .catch((错误)=>Promise.reject(错误)); }; 返回{ 用户名, 密码, 登录用户, 注销用户, 刷新令牌, 盖托多斯, 待办事项, loggedInUser, }; }, }; #认证部门{ 利润率:20px 20px; 文本对齐:居中; } #authenticationDiv表单{ 显示:内联; } #authenticationDiv按钮{ 利润率:0px 20px; 填充:0px 18px; 背景色:白色; 边框:2个实心耐火砖; 颜色:耐火砖; 过渡:0.3s; /*悬停时会逐渐消失*/ } #authenticationDiv按钮:悬停{ 背景颜色:耐火砖; 颜色:rgb(255、255、255); } #物流信息{ 利润率:10px 20px; 填充物:5px10px; 背景色:rgba(237,1,1,0.467); 颜色:白色; }