为什么 vue-resource 在 XHR 中不发送 cookie,所以会话不起作用?



这是最初的问题:

在Django中,如果视图函数有csrf_exempt装饰,我如何使会话工作?

我使用Django作为restful API,发现如果视图具有csrf_exempt装饰,则会话不起作用。

这里有一些代码:

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

当我在其他视图中打印request.session.get('username'(时,我发现request.session根本不会更改。

但是,如果没有csrf_exempt,它是有效的:

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

我该怎么修?

事实证明,它与后端无关。是vue资源导致了这个问题。

我提出的帖子请求是:

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.
})

事实上,浏览器中的cookie根本没有发送。因此,后端没有收到"sessionid",也无法访问会话。这就是Django中的会话不起作用的原因。

为了解决这个问题,XHR中有一个名为">withCredential"的选项,这将允许浏览器发送cookie。

然后代码变为:

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.
})

它会起作用的。

最新更新