【发布时间】:2020-11-14 00:14:07
【问题描述】:
在将表单从我的 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>
【问题讨论】:
标签: javascript vue.js django-rest-framework