我分别拥有Vue应用和Django rest框架api。 一个在localhost:8080(vue应用程序)上,其余的api在localhost:8000。
因此,我创建了一个APIView,该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应用设置用户会话?
在此先感谢您所缺乏的知识。