AngularJS对Django的API调用,GET工作但禁止POST

时间:2015-11-10 07:54:14

标签: angularjs django rest django-rest-framework

我有一个AngularJS前端和一个Django后端。

前端使用以下两个$ 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

3 个答案:

答案 0 :(得分:0)

添加:

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

在运动员课程之前。

答案 1 :(得分:0)

如果您正在使用基于会话的身份验证,则需要确保已发送CSRF。

Django文档有关于如何执行此操作的完整说明:https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

请注意,必须有一些角度插件可以处理,虽然我没有人可以推荐,因为我没有为我的API使用角度。

答案 2 :(得分:0)

你能发布你得到的完整错误吗? Django通常会告诉您为什么您的请求被拒绝。

如果问题是CSRF,请查看:

XSRF headers not being set in AngularJS

解决了我访问django后端的问题。