не удалось настроить axios с помощью django rest auth для входа в систему и получения токена аутентификации

#vue.js #django-rest-framework #axios #django-rest-auth

#vue.js #django-rest-framework #axios #django-rest-auth

Вопрос:

Я пробовал эти коды:

src/api/auth.js

 import session from "./session";

export default {
  login(Username, Password) {
    return session.post("/auth/login/", { Username, Password });
  },
  logout() {
    return session.post("/auth/logout/", {});
  },
  createAccount(username, password1, password2, email) {
    return session.post("/registration/", {
      username,
      password1,
      password2,
      email
    });
  },
  changeAccountPassword(password1, password2) {
    return session.post("/auth/password/change/", { password1, password2 });
  },
  sendAccountPasswordResetEmail(email) {
    return session.post("/auth/password/reset/", { email });
  },
  resetAccountPassword(uid, token, new_password1, new_password2) {
    // eslint-disable-line camelcase
    return session.post("/auth/password/reset/confirm/", {
      uid,
      token,
      new_password1,
      new_password2
    });
  },
  getAccountDetails() {
    return session.get("/auth/user/");
  },
  updateAccountDetails(data) {
    return session.patch("/auth/user/", data);
  },
  verifyAccountEmail(key) {
    return session.post("/registration/verify-email/", { key });
  }
};
  

src/session.js

 import axios from "axios";

const CSRF_COOKIE_NAME = "csrftoken";
const CSRF_HEADER_NAME = "X-CSRFToken";

const session = axios.create({
  xsrfCookieName: CSRF_COOKIE_NAME,
  xsrfHeaderName: CSRF_HEADER_NAME
});

export default session;
  

src/store/auth.js

 import auth from "../api/auth";
import session from "../api/session";
import {
  LOGIN_BEGIN,
  LOGIN_FAILURE,
  LOGIN_SUCCESS,
  LOGOUT,
  REMOVE_TOKEN,
  SET_TOKEN
} from "./types";

const TOKEN_STORAGE_KEY = "TOKEN_STORAGE_KEY";

const initialState = {
  authenticating: false,
  error: false,
  token: null
};

const getters = {
  isAuthenticated: state => !!state.token
};

const actions = {
  login({ commit }, { username, password }) {
    commit(LOGIN_BEGIN);
    return auth
      .login(username, password)
      .then(({ data }) => commit(SET_TOKEN, data.key))
      .then(() => commit(LOGIN_SUCCESS))
      .catch(() => commit(LOGIN_FAILURE));
  },
  logout({ commit }) {
    return auth
      .logout()
      .then(() => commit(LOGOUT))
      .finally(() => commit(REMOVE_TOKEN));
  },
  initialize({ commit }) {
    const token = localStorage.getItem(TOKEN_STORAGE_KEY);

    if (token) {
      commit(SET_TOKEN, token);
    } else {
      commit(REMOVE_TOKEN);
    }
  }
};

const mutations = {
  [LOGIN_BEGIN](state) {
    state.authenticating = true;
    state.error = false;
  },
  [LOGIN_FAILURE](state) {
    state.authenticating = false;
    state.error = true;
  },
  [LOGIN_SUCCESS](state) {
    state.authenticating = false;
    state.error = false;
  },
  [LOGOUT](state) {
    state.authenticating = false;
    state.error = false;
  },
  [SET_TOKEN](state, token) {
    localStorage.setItem(TOKEN_STORAGE_KEY, token);
    session.defaults.headers.Authorization = `Token ${token}`;
    state.token = token;
  },
  [REMOVE_TOKEN](state) {
    localStorage.removeItem(TOKEN_STORAGE_KEY);
    delete session.defaults.headers.Authorization;
    state.token = null;
  }
};

export default {
  namespaced: true,
  state: initialState,
  getters,
  actions,
  mutations
};
  

src/views/Login.vue

 <template>
  <div>
    <form class="login" @submit.prevent="login">
      <h1>Sign in</h1>
      <label>Username</label>
      <input required v-model="Username" type="text" placeholder="Name" />
      <label>Password</label>
      <input
        required
        v-model="Password"
        type="password"
        placeholder="Password"
      />
      <hr />
      <button type="submit">Login</button>
    </form>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      Username: "",
      Password: ""
    };
  },
  methods: {
    /*login() {
      let Username = this.Username;
      let Password = this.Password;
      this.$store
        .dispatch("auth/login", { Username, Password })
        .then(() => this.$router.push("/"))
        .catch(err => console.log(err));*/
    login({ Username, Password }) {
      const API_URL = "http://127.0.0.1:8000";
      const url = `${API_URL}/auth/login/`;
      return axios
        .post(url, { Username, Password })
        .then(() => this.$router.push("/"))
        .catch(err => console.log(err));
    }
  },
  mounted() {
    this.login();
  }
};
</script>
  

first, I tried using the auth service but the failure was OPTIONS not POST.
then i used axios directly to post user and get token, but then the failure was method not allowed, I do not know what is the hidden process, can you explain please?

app.vue

 <template>
  <div id="app">
    <navbar v-if="isAuthenticated"></navbar>
    <router-view></router-view>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import Navbar from "./components/Navbar";

export default {
  name: "app",
  components: {
    Navbar
  },
  computed: mapGetters("auth", ["isAuthenticated"])
};
</script>
  

router.js

 import Vue from "vue";
import Router from "vue-router";
import About from "./views/About";
import Home from "./views/Home";
import Login from "./views/Login";
import Lost from "./views/Lost";
import PasswordReset from "./views/PasswordReset";
import PasswordResetConfirm from "./views/PasswordResetConfirm";
import Register from "./views/Register";
import VerifyEmail from "./views/VerifyEmail";

import store from "./store/index";

const requireAuthenticated = (to, from, next) => {
  store.dispatch("auth/initialize").then(() => {
    if (!store.getters["auth/isAuthenticated"]) {
      next("/login");
    } else {
      next();
    }
  });
};

const requireUnauthenticated = (to, from, next) => {
  store.dispatch("auth/initialize").then(() => {
    if (store.getters["auth/isAuthenticated"]) {
      next("/home");
    } else {
      next();
    }
  });
};

const redirectLogout = (to, from, next) => {
  store.dispatch("auth/logout").then(() => next("/login"));
};

Vue.use(Router);

export default new Router({
  saveScrollPosition: true,
  routes: [
    {
      path: "/",
      redirect: "/home"
    },
    {
      path: "/about",
      component: About,
      beforeEnter: requireAuthenticated
    },
    {
      path: "/home",
      component: Home,
      beforeEnter: requireAuthenticated
    },
    {
      path: "/password_reset",
      component: PasswordReset
    },
    {
      path: "/password_reset/:uid/:token",
      component: PasswordResetConfirm
    },
    {
      path: "/register",
      component: Register
    },
    {
      path: "/register/:key",
      component: VerifyEmail
    },
    {
      path: "/login",
      component: Login,
      beforeEnter: requireUnauthenticated
    },
    {
      path: "/logout",
      beforeEnter: redirectLogout
    },
    {
      path: "*",
      component: Lost
    }
  ]
});
  

main.js

 import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";
import axios from "axios";
import Axios from "axios";
import VueAxios from "vue-axios";
import Vuex from "vuex";

Vue.use(Vuex);
Vue.use(VueAxios, axios);
//Vue.config.productionTip = false;
Vue.prototype.$http = Axios;
const token = localStorage.getItem("token");
if (token) {
  Vue.prototype.$http.defaults.headers.common["Authorization"] = token;
}

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");
  

ссылки:

 https://www.techiediaries.com/vue-axios-tutorial/
https://scotch.io/tutorials/handling-authentication-in-vue-using-vuex
https://github.com/jakemcdermott/vue-django-rest-auth
  

Ответ №1:

Скорее всего, проблемы с CORS.

Если вы обслуживаете сервер vue на другом порту, а не на сервере django, вам необходимо установить правильные настройки CORS.

Пожалуйста, обратитесь к https://github.com/ottoyiu/django-cors-headers /

Ответ №2:

хотя кажется, что мой код немного уродлив, потому что я смешал кучу репозиториев, но, по крайней мере, я успешно сделал это. Я использовал

 npm install qs
  

затем импортируйте его, затем:

 var username = payload.credential.username;
var password = payload.credential.password;
  

затем редактирование

 axios.post(url, qs.stringify({ username, password })
  

и это сработало.