0

我分别有 Vue 应用程序和 Django rest 框架 api。一个在 localhost:8080(vue 应用程序)上,其余的 api 在 localhost:8000 上。

因此,我创建了一个 APIView,它应该在用户发出发布请求时登录:

class LoginUserAPIView(APIView):
    permission_classes = () # login should be accessed by anyone, no restrictions.
    def post(self, request, format=None):
        username = request.data['username']
        password = request.data['password']

        user = authenticate(username=username, password=password)

        if user is not None:
            login(request, user)
            user = UserSerializer(user)
            return Response({'success': 'Logged in', 'user': user.data})
        return Response({'wrong': 'username or password not correct, try again'}, status=status.HTTP_401_UNAUTHORIZED)

我正在尝试使用 axios 从 django 获取用户会话:

login() {
      this.isLoading = true;
      return axios({
        method: 'post',
        url: 'http://localhost:8000/api/login_user',
        data: {
          username: this.name,
          password: this.password
        },
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        this.$store.commit('loginAuth', true); // setting isAuth to true in vuex store.
        this.$store.commit('setUser', response.data.user); // to access the user object since I don't use django templates
        this.$router.push({name: 'page'}); // redirect to random test page that requires authorization so I can see if everything went fine.
      })
      .catch(err => {
        console.error(err);
        if (err.response.status == 401) {
          alert(err.response.data.wrong);
          this.isLoading = false;
        }
      })

但我很天真,我认为这会起作用,所以当我检查 vue 应用程序是否有任何 cookie 或会话时,什么也没有。

如何为单独的 vue 应用程序设置用户会话?

在此先感谢,我为我缺乏知识而道歉。

4

0 回答 0