我有一个使用Django后端和Angular前端的应用程序。
现在,它们已经连接,我可以从Django获取数据并在Angular中显示,并且可以向Django发送post请求。
但是,问题出在Django的CSRF令牌上。尽管我知道这样做不安全,但我禁用了Django中的CSRF中间件以便请求可以被处理。
以下是进行post请求的方法:
loadQuestion(id): Observable<any> {
const body = {'choice': 'teseted with post method'};
return this.http.post(this.baseUrl + id + '/vote', {headers: this.header, withCredentials: true, });
}
我根据这个链接做了一些更改。
HttpClientXsrfModule.withConfig({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' })
但是我遇到了这个错误。
app.module.ts: 26未捕获的类型错误:_angular_common_http__WEBPACK_IMPORTED_MODULE_3__.HttpClientXsrfModule.withConfig 不是一个函数
所以我基于这个链接进行了更改。
HttpClientXsrfModule.withOptions({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' })
这是我的Django函数返回数据的方法,正如我所说,当我禁用CSRF中间件时它可以正常工作,因此我应该解决CSRF问题并将其传递给Angular请求。
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=4)
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return HttpResponse("You didn't select a choice.")
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponse(request)
我评论的中间件代码:
'django.middleware.csrf.CsrfViewMiddleware'
错误是CSRF验证失败。请求已终止。
更新
我使用了CORS Origin,这是我的Django配置
CORS_ORIGIN_ALLOW_ALL = True
CSRF_COOKIE_SECURE = False
CSRF_USE_SESSIONS = False
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'X-CSRFToken',
'x-csrftoken',
'X-XSRF-TOKEN',
'XSRF-TOKEN',
'csrfmiddlewaretoken',
'csrftoken',
'X-CSRF'
)
CORS_ALLOW_CREDENTIALS = True
http://localhost:4200/
上,而 Django 在http://localhost:8000/
上。 - Nasser Ali Karimi