【问题标题】:Cant get AngularJS's $http.post data in Django无法在 Django 中获取 AngularJS $http.post 数据
【发布时间】:2014-12-31 19:15:10
【问题描述】:

我知道这是一个非常基本的问题,但是在浪费了我一整天之后,我才问这个问题。我只是使用以下 AngularJS 代码向 Django 发送数据:

$http.post('/data/creation', 
                    {
                html: 'a'

            }).
              success(function(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                  console.log(data);
                  console.log(status);
                  console.log(headers);
                  console.log(config);
              }).
              error(function(data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                  console.log(status);
                  console.log(data);
              });

在 Django 中:

@csrf_exempt
def snippets_post(request):
    html = False
    css = False
    js = False
    JSONdata = False
    response = "You're looking at the results of question %s."
    if request.method == 'POST':
        try:
            JSONdata = request.POST.get('data', False) # it was [] in actual
        except:
            JSONdata = 'ERROR'

    return HttpResponse(JSONdata)

我得到 False 作为响应,“通过在 POST.get 中将数据替换为 html,结果相同”。我不知道这里出了什么问题。任何人都可以在这里帮助我吗?

谢谢

【问题讨论】:

  • 能否请您返回一个静态值并检查.. return HttpResponse("post value") ..我怀疑该 URL 是否命中了这个 sn-p 或某个地方?
  • 通信进展顺利,我得到 False 因为 POST.get 无法获取“数据”或“html”。问题是如何得到它?
  • 请通过单击 F12 使用 firebug 或 chrome 网络选项卡跟踪请求,并在请求处理时查看 url 是否包含 html/data..如果存在,则问题出在您的服务器端代码中...
  • 当然,正在检查数据,它的一些 python/django 问题,一些解析等,我在这里缺少,但不能说。
  • 删除所有行,然后像这个请求一样简单地尝试。POST['data'] ...检查这个线程stackoverflow.com/questions/464040/…

标签: python django angularjs angularjs-http


【解决方案1】:

实际上,当我们使用 $http 的 POST 从 AngularJs 发送数据时,它会将 content-type = "application/json" 的数据发送到服务器。而且 Django 不理解这种格式。所以你无法获取发送的数据。

解决方案是使用以下配置更改内容类型标题:

    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}]);

【讨论】:

  • 有趣!很高兴知道这一点。感谢您的告知:)
  • 谢谢,这也适用于 Turbogears 框架
猜你喜欢
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多