HankelBao
HankelBao

Reputation: 31

Why vue-resource doesn't sent cookies in XHR so sessions don't work?

This was the original question:

In Django, how can I make session work if the view function has a csrf_exempt decoration?

I'm using Django as restful APIs and found that session doesn't work if a view has a csrf_exempt decoration.

Here is some code:

@csrf_exempt
def scorer_login(request):
    request.session['username'] = request.POST['username']

I found that request.session doesn't change at all when I print request.session.get('username') in other views.

However, if there isn't csrf_exempt, it works:

def scorer_login(request):
    request.session['username'] = 'test_username'

How can I fix it?

Upvotes: 0

Views: 776

Answers (1)

HankelBao
HankelBao

Reputation: 31

It turns out that it has nothing to do with the back end. It's vue-resource that lead to the problem.

The Post Request I made was:

this.$http.post('http://localhost:8000/scorer/signin', {
    'username': this.username,
    'password': this.password
}, {emulateJSON: true}).then( response => {
     return response.json();
}).then( json => {
    // some other stuff.
})

In fact, the cookies in the browser didn't send at all. As a result, the back end didn't receive 'sessionid' and it couldn't get access to sessions. This is the reason why sessions in Django aren't working.

To solve it, there is an option named "withCredential" in XHR and this will let the browser send cookies.

The code then becomes:

this.$http.post('http://localhost:8000/scorer/signin', {
    'username': this.username,
    'password': this.password
}, {emulateJSON: true, withCredentials: true}).then( response => {
     return response.json();
}).then( json => {
    // some other stuff.
})

And it will work.

Upvotes: 3

Related Questions