2012-10-25 105 views
3

嘗試後這個Django的Tastypie API: http://lit-hollows-9760.herokuapp.com/api/food內無法在Django的Tastypie跨域XHR

我有這樣的中間件安裝允許跨域XHR: https://gist.github.com/1369619

from django import http 

try: 
    from django.conf import settings 
    XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS 
    XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS 
    XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS 
    XS_SHARING_ALLOWED_CREDENTIALS = settings.XS_SHARING_ALLOWED_CREDENTIALS 
except AttributeError: 
    XS_SHARING_ALLOWED_ORIGINS = '*' 
    XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'] 
    XS_SHARING_ALLOWED_HEADERS = ['Origin', 'Content-Type', 'Accept'] 
    XS_SHARING_ALLOWED_CREDENTIALS = 'true' 


class XsSharing(object): 
    """ 
    This middleware allows cross-domain XHR using the html5 postMessage API. 

    Access-Control-Allow-Origin: http://foo.example 
    Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE 

    Based off https://gist.github.com/426829 
    """ 
    def process_request(self, request): 
     if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META: 
      print request.META 
      response = http.HttpResponse() 
      response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS 
      response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS) 
      response['Access-Control-Allow-Headers'] = ",".join(XS_SHARING_ALLOWED_HEADERS) 
      response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS 
      return response 

     return None 

    def process_response(self, request, response): 
     #print request.META 
     response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS 
     response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS) 
     response['Access-Control-Allow-Headers'] = ",".join(XS_SHARING_ALLOWED_HEADERS) 
     response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS 
     #print response 
     return response 

我可以使用JSONP來檢索GET請求,但我無法弄清楚如何讓POST工作。我只是一個301而已,沒有更多。

"OPTIONS /api/food HTTP/1.1" 301 0 

演示:http://jsfiddle.net/rob_balfre/vgrJD/

這是我如何打電話POST使用jQuery:

$.ajax({ 
    type: 'POST', 
    url: 'http://lit-hollows-9760.herokuapp.com/api/food', 
    data: '{"name": "Tapas"}', 
    success: console.log('jquery worked'), 
    dataType: "application/json", 
    processData: false, 
    contentType: "application/json" 
}); 
+0

在一個非常簡單我們從Tastypie Serializer中得到這個錯誤:「未找到指定類型'jsonp'的內容類型。 「任何見解? – sgimeno

+0

我們發現在不同的Django中間件中使用的順序在達到XSSharing之前就篡改了我們的請求。 – sgimeno

回答

3

我需要JSON添加到:

serializer = Serializer(formats=['jsonp', 'json']) 

的tastypie資源

+0

您能分享一些鏈接或您用於解決此問題的資源。謝謝 – sgimeno