3

我知道这是一个非常基本的问题,但是在浪费了我一整天之后,我问了这个问题。我只是使用以下 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,结果是相同的”。我不知道这里出了什么问题。任何人都可以在这里帮助我吗?

谢谢

4

1 回答 1

5

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

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

    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}]);
于 2014-11-05T15:28:52.180 回答