angular2 / Django rest应用程序浏览器在应用程序登录后要求登录

时间:2017-03-14 11:42:06

标签: django angular django-rest-framework

我正在构建一个前端为angular2的应用程序,而Django则在后端构建。即使在我登录我的应用程序后,浏览器又要求再次登录,如下所示:

enter image description here

每天都会发生这种情况,但不会在同一天连续登录。为什么会这样?

我的Django休息配置代码:

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

]
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.BasicAuthentication',
       'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

和angular2服务:

  login(username: string, password: string) {

    let body = JSON.stringify({
      'username' : username, 
      'password': password
    });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this._authenticationUrl + 'login/', body, options)
    .map(this.extractData)
    .catch(this.handleError)
  }

为什么会这样?

2 个答案:

答案 0 :(得分:0)

我的代码中有以下内容导致问题:

   function generateNumber() {
  var sResultat
  var cells = ["FOR", "DEX", "CON", "INT", "SAG", "CHA"]
  cells.forEach(function(cell) {
    sResultat = Math.round(Math.random() * 18) + 1;
    document.getElementsByClassName(cell)[0].innerText = sResultat
  })
}

generateNumber()

答案 1 :(得分:0)

你应该删除

final

来自'rest_framework.authentication.BasicAuthentication', ,并保留

DEFAULT_AUTHENTICATION_CLASSES
'rest_framework.permissions.IsAuthenticated', 中的