gpt4 book ai didi

jquery - 无法POST到Django Tastypie跨域XHR

转载 作者:行者123 更新时间:2023-12-01 01:16:49 25 4
gpt4 key购买 nike

尝试发布到此 Django Tastypie API: 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"
});

最佳答案

我需要将 json 添加到:

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

Tastypie 资源

关于jquery - 无法POST到Django Tastypie跨域XHR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13069828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com