【问题标题】:Sending post data from angularjs to django as JSON and not as raw content将来自 angularjs 的帖子数据作为 JSON 而不是作为原始内容发送到 django
【发布时间】:2013-09-24 10:28:51
【问题描述】:

我有这样的要求:

$http({ 
    method: 'POST', 
    url: '/url/', 
    data: 'test=data'
})

在我的 django 视图中:

class SomeClass(View):
    def get(self, request):
        return HttpResponse("Hello")
    def post(self, request):
        print request.post
        print request.body
        return HttpResponse("Done")

所以当我执行request.POST 时,我得到一个空查询字典:<QueryDict: {}>

但我的request.body 有:test=data

所以我相信 django 将数据作为 url 编码参数而不是作为字典接收。

如何以 JSON/Dict 格式发送或接收这些数据?

【问题讨论】:

标签: python django angularjs http-post


【解决方案1】:

调用ajax时,请求正文中收到编码的json字符串,所以需要使用python的json模块解码得到python dict:

json.loads(request.body)

【讨论】:

  • 我喜欢这个解决方案,因为我可以使用 AngularJS 的设计,而不是像我习惯使用 jQuery 那样破解它来工作。
  • 漂亮的惯用方法。
  • 如果您使用 Angular 4 和 DRF,请使用 request.data
【解决方案2】:

在我的情况下是这样的

$http({
    url: '/url/',
    method: "POST",
    data: $.param(params),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
})

或者更漂亮的变体:

app.config ($httpProvider) ->
    ...
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

然后

$scope.save_result = $http.post('/url/', $.param(params))

http://www.daveoncode.com/2013/10/17/how-to-make-angularjs-and-django-play-nice-together/

【讨论】:

    【解决方案3】:

    我正在使用 zope2,我使用 simplejson 将请求 json 解码为 python 字典:

    request_dict = simplejson.loads(request.get('BODY','')
    

    它对我来说工作正常。通过这种方式,我可以使用 angularjs 默认的 json 请求,而不是将其转换为表单 post。

    【讨论】:

    • 为我节省了一天
    【解决方案4】:

    我通过创建装饰器稍微改进了 mariodev 的解决方案:

    # Must decode body of angular's JSON post requests
    def json_body_decoder(my_func):
        def inner_func(request, *args, **kwargs):
            body = request.body.decode("utf-8")
            request.POST = json.loads(body)
            return my_func(request, *args, **kwargs)
        return inner_func
    
     @json_body_decoder
     def request_handler(request):
         # request.POST is a dictionary containing the decoded body of the request
    

    现在,每当我创建处理 application/json 中的发布数据的请求处理程序时,我只需添加 @json_body_decoder 装饰器。

    【讨论】:

      【解决方案5】:

      对于 Angular 4 和 Django Rest Framework,使用 request.data 获取 json 对象。

      喜欢:

      posted_data = request.data

      【讨论】:

        【解决方案6】:

        $http 服务需要一个 JS 对象,而不是字符串。试试这个:

        $http({ 
            method: 'POST', 
            url: '/url/', 
            data: {test: 'data'}
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-10-13
          • 1970-01-01
          • 2012-10-25
          • 2019-06-18
          • 1970-01-01
          • 2014-02-05
          • 2014-05-29
          相关资源
          最近更新 更多