このDjangoTastypieAPIに投稿しようとしています:http: //lit-hollows-9760.herokuapp.com/api/food
クロスドメイン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/
これが私がjQueryでPOSTを呼び出す方法です:
$.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"
});