从不同的地址调用Django restframework不工作

时间:2015-10-29 09:12:40

标签: javascript python ajax django django-rest-framework

我目前正在关注以下教程:http://www.django-rest-framework.org/为我的django应用程序创建一个restful API,托管在apache上。然后我想用ajax调用api并在我的页面上显示数据。

使用url.py中教程中的相同代码:

from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

调用api的ajax代码:

(function() {
var monsterAPI = "http://10.0.106.14/api/monsters/?format=json";

alert("DEBUG1");
$.getJSON( monsterAPI, {
 format: "json"
})
.done(function( monsters ) {
  alert("DEBUG2");

});
})();

当我从同一个apache服务器(//10.0.106.14/temp/)上托管的html调用这个ajax代码时,它可以工作,我得到警告" DEBUG2"。 但是当我从不同机器(//127.0.0.1/temp/)从本地服务器运行html调用api时,它到达了#34; DEBUG1"并停了下来

我错过了什么吗? :(

在settings.py上添加身份验证和权限也无法解决问题:

 REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
    # 'DEFAULT_AUTHENTICATION_CLASSES': [
    #     'rest_framework.authentication.BasicAuthentication',
    #     'rest_framework.authentication.SessionAuthentication',
    # ]
 }

2 个答案:

答案 0 :(得分:0)

据我所知,您应该在get-request中指定port。如果您在端口8899上启动服务器,则应该请求“http://127.0.0.1:8899/users/?format=json

答案 1 :(得分:0)

如果您尝试从127.0.0.1(默认端口80)访问127.0.0.1:8899,则可能会遇到跨源资源共享问题。 http://www.django-rest-framework.org/topics/ajax-csrf-cors/#cors比我对此主题的解释更好,并为此提供了解决方法。