2015-11-10 40 views
0

我有一個AngularJS前端和一個Django後端。AngularJS rest Django的API調用,GET工作,但POST被禁止

前端使用以下兩種$ HTTP調用調用後端:

athleticsApp.controller('athletesListController', ['$scope', '$http', function($scope, $http) { 
    $scope.athletes = []; 

    $scope.getAthletes = function(){ 
     $http 
      .get('http://serverip:8666/athletics/athletes/') 
      .success(function(result) { 
       $scope.athletes = result; 
      }) 
      .error(function(data, status) { 
       console.log(data); 
       console.log(status); 
      }); 
    } 

    $scope.init = function() { 
     $scope.getAthletes(); 
    } 

    $scope.init(); 

}]); 

athleticsApp.controller('athleteNewController', ['$scope', '$http', function($scope, $http) { 
    $scope.athlete = { 
     firstName : '', 
     lastName : '' 
    }; 

    $scope.postNewAthlete = function(){ 
     $http 
      .post('http://serverip:8666/athletics/athletes/', $scope.athlete) 
      .success(function(result) { 
       // set url fraction identifier to list athletes 
      }) 
    } 
}]); 

get調用是成功的。 POST調用會生成以下錯誤:

POST http://serverip:8666/athletics/athletes/ 403 (FORBIDDEN)

它爲什麼會產生錯誤?

Django的代碼如下所示:

urls.py

from django.conf.urls import patterns, url 

from views import Athletes 

urlpatterns = [ 
    url(r'^athletes/', Athletes.as_view()), 
] 

views.py

from rest_framework.response import Response 
from rest_framework.views import APIView 
from .models import Athlete 
from django.shortcuts import get_object_or_404, render 

from athletics.serializers import AthleteSerializer 

class Athletes(APIView): 
    def get(self, request, format=None): 
     all_athletes = Athlete.objects.all() 
     serializer = AthleteSerializer(all_athletes, many=True) 
     return Response(serializer.data) 

    def post(self, request, format=None): 
     serializer = AthleteSerializer(data=request.data) 
     if serializer.is_valid(raise_exception=True): 
      creation_data = serializer.save() 
      return Response() 

serializers.py

class AthleteSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Athlete 
     fields = (
      'first_name', 
      'last_name' 
     ) 

settings.py

# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 
import os 

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 


# Quick-start development settings - unsuitable for production 
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ 

# SECURITY WARNING: keep the secret key used in production secret! 
SECRET_KEY = 'characters' 

# SECURITY WARNING: don't run with debug turned on in production! 
DEBUG = True 

INTERNAL_IPS = (
    'myip' 
) 

CORS_ORIGIN_ALLOW_ALL = True 

ALLOWED_HOSTS = [] 


# Application definition 

REQUIRED_APPS = (
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    # Third party apps 
    'rest_framework', 

) 

PROJECT_APPS = (
    # This project 
    'athletics', 
    'testetics', 
) 

INSTALLED_APPS = REQUIRED_APPS + PROJECT_APPS 

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

    'django.contrib.messages.middleware.MessageMiddleware', 
    'corsheaders.middleware.CorsMiddleware', 

) 

ROOT_URLCONF = 'mysitedjango.urls' 

TEMPLATES = [ 
    { 
     'BACKEND': 'django.template.backends.django.DjangoTemplates', 
     'DIRS': [], 
     'APP_DIRS': True, 
     'OPTIONS': { 
      'context_processors': [ 
       'django.template.context_processors.debug', 
       'django.template.context_processors.request', 
       'django.contrib.auth.context_processors.auth', 
       'django.contrib.messages.context_processors.messages', 
      ], 
     }, 
    }, 
] 

WSGI_APPLICATION = 'mysitedjango.wsgi.application' 


# Database 
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.sqlite3', 
     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    } 
} 


# Internationalization 
# https://docs.djangoproject.com/en/1.8/topics/i18n/ 

LANGUAGE_CODE = 'en-us' 

TIME_ZONE = 'Europe/Stockholm' 

USE_I18N = True 

USE_L10N = True 

USE_TZ = True 


# Static files (CSS, JavaScript, Images) 
# https://docs.djangoproject.com/en/1.8/howto/static-files/ 

STATIC_URL = '/static/' 

編輯:我添加settings.py

+0

你的設置呢?你能提供'DEFAULT_PERMISSION_CLASSES'和'DEFAULT_AUTHENTICATION_CLASSES'嗎? – DevilPinky

+0

@DevilPinky:我以前沒有聽說過他們。我沒有將這些設置輸入到我的settings.py中,所以我想我具有默認值。 – user1283776

+0

你可以請他們發佈? – DevilPinky

回答

0

地址:

@api_view(['POST', 'GET']) 

只是你的運動員上課前。

+0

當您使用API​​View時,不需要指定。 – DevilPinky

0

如果您使用基於會話的身份驗證,則需要確保發送CSRF。

Django文檔對如何做一個充分的解釋:https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

需要注意的是,必須有角的插件處理已經雖然我沒有一個建議,因爲我沒有使用的角度爲我蜜蜂。

0

你能發佈你得到的全部錯誤嗎? Django通常會告訴你爲什麼你的請求被拒絕。

如果問題是CSRF,看看:

XSRF headers not being set in AngularJS

這解決了我曾訪問Django的後端問題。

+0

我不明白如何從該網站添加CSFR令牌。我如何使用Django進行設置?我如何將它添加到AngularJS中的發佈請求中? – user1283776

+0

在您的設置中,您有'django.middleware.csrf.CsrfViewMiddleware',它使用cookie啓用csrf。在angularjs端添加鏈接代碼 –

+0

如果你可以檢查併發布你從後端得到的響應,這將是非常有用的,因爲django通常會告訴你爲什麼它不接受你的請求 –

相關問題