django-tastypie和跨域json

django-tastypie和跨域json,django,json,node.js,express,Django,Json,Node.js,Express,在localhost:8000上运行django dev服务器,在localhost:3000上运行nodejs服务器。我想将json导入nodejs服务器,但出现以下错误: 无法加载XMLHttpRequest . 起源 访问控制允许原点不允许 这是我第一次尝试跨领域的乐趣,所以我已经超出了我的深度 我已将其添加到节点(expressjs)中的路由中 我遗漏了什么/做错了什么?数据提供者需要为跨域请求设置策略(而不是像您的expressjs代码片段所建议的客户端) 发布了一个简单的Django

在localhost:8000上运行django dev服务器,在localhost:3000上运行nodejs服务器。我想将json导入nodejs服务器,但出现以下错误:

无法加载XMLHttpRequest . 起源 访问控制允许原点不允许

这是我第一次尝试跨领域的乐趣,所以我已经超出了我的深度

我已将其添加到节点(expressjs)中的路由中

我遗漏了什么/做错了什么?

数据提供者需要为跨域请求设置策略(而不是像您的expressjs代码片段所建议的客户端)

发布了一个简单的Django中间件的要点,该中间件负责注入所需的头文件:

Middlware允许您的django服务器适当地响应跨域XHR(PostMessageHTML5API)

    • 您也可以使用

      -这段代码非常有用,但是在使用主干网向django服务器发送邮件时,我必须将请求时的访问控制请求头与响应时的访问控制允许头进行匹配

      咖啡:

      auth = (xhr) ->
      xhr['xhrFields']= {withCredentials: true}
      xhr.setRequestHeader('Access-Control-Allow-Credentials', 'true' )
      xhr.header('Access-Control-Allow-Origin', "*")
      xhr.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS')
      xhr.header('Access-Control-Allow-Headers', 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control')  
      
      python:加上一行

      def process_request(self, request):
      
          if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in 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'] = "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"
              return response
      
          return None          
      

      希望这是有用的

      在ajax POST代码中设置数据类型:“text”而不是“jsonp”对我来说很有用。

      是一个TastyPie资源基类。任何将此子类化的资源都可以跨域访问

      它与其他类似,但会将CORS头添加到TastyPie资源可能给出的所有响应中。这包括错误响应和立即响应异常

      from tastypie.resources import Resource
      from tastypie.exceptions import ImmediateHttpResponse
      from django.http import HttpResponse
      
      
      class CorsResource(Resource):
      
          """ adds CORS headers for cross-domain requests """
      
          def patch_response(self, response):
      
              allowed_headers = ['Content-Type', 'Authorization']
      
              response['Access-Control-Allow-Origin'] = '*'
              response['Access-Control-Allow-Headers'] = ','.join(allowed_headers)
              return response
      
          def dispatch(self, *args, **kwargs):
              """ calls super and patches resonse headers
                  or
                  catches ImmediateHttpResponse, patches headers and re-raises
              """
      
              try:
                  response = super(CorsResource, self).dispatch(*args, **kwargs)
                  return self.patch_response(response)
              except ImmediateHttpResponse, e:
                  response = self.patch_response(e.response)
                  # re-raise - we could return a response but then anthing wrapping
                  # this and expecting an exception would be confused
                  raise ImmediateHttpResponse(response)
      
          def method_check(self, request, allowed=None):
              """ Handle OPTIONS requests """
              if request.method.upper() == 'OPTIONS':
      
                  if allowed is None:
                      allowed = []
      
                  allows = ','.join([s.upper() for s in allowed])
      
                  response = HttpResponse(allows)
                  response['Allow'] = allows
                  raise ImmediateHttpResponse(response=response)
      
              return super(CorsResource, self).method_check(request, allowed)
      

      这里有一个友好的、可配置的Django模块:

      我正在使用gist,但不适合我。试图通过简单的jquery加载django/python后端在回望时公开的简单json。我也在使用$.getJSON方法。并且在我的中间件设置中添加了提到的中间件。有什么可能是错的?是否有添加中间件的特定顺序?或者我是否也需要在每个响应中显式设置头?(看起来不像是中间件的代码)。或者我需要修改它来处理json mimetype吗?提前感谢。我认为需要在响应和请求中设置标题。这太棒了!但是如何自定义回调名称?在URL中包含
      callback
      参数<代码>http://127.0.0.1:8000/api/presentation?format=jsonp&callback=foo。这对我很有效。刚刚在类标题中将Resource更改为ModelResource。
      def process_request(self, request):
      
          if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in 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'] = "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"
              return response
      
          return None          
      
      from tastypie.resources import Resource
      from tastypie.exceptions import ImmediateHttpResponse
      from django.http import HttpResponse
      
      
      class CorsResource(Resource):
      
          """ adds CORS headers for cross-domain requests """
      
          def patch_response(self, response):
      
              allowed_headers = ['Content-Type', 'Authorization']
      
              response['Access-Control-Allow-Origin'] = '*'
              response['Access-Control-Allow-Headers'] = ','.join(allowed_headers)
              return response
      
          def dispatch(self, *args, **kwargs):
              """ calls super and patches resonse headers
                  or
                  catches ImmediateHttpResponse, patches headers and re-raises
              """
      
              try:
                  response = super(CorsResource, self).dispatch(*args, **kwargs)
                  return self.patch_response(response)
              except ImmediateHttpResponse, e:
                  response = self.patch_response(e.response)
                  # re-raise - we could return a response but then anthing wrapping
                  # this and expecting an exception would be confused
                  raise ImmediateHttpResponse(response)
      
          def method_check(self, request, allowed=None):
              """ Handle OPTIONS requests """
              if request.method.upper() == 'OPTIONS':
      
                  if allowed is None:
                      allowed = []
      
                  allows = ','.join([s.upper() for s in allowed])
      
                  response = HttpResponse(allows)
                  response['Allow'] = allows
                  raise ImmediateHttpResponse(response=response)
      
              return super(CorsResource, self).method_check(request, allowed)