我正在尝试将一些数据从AngualrJS发布到Django后端。
我的代码如下所示:
角
$http({
method: 'POST',
url: 'path/to/django/',
data: $scope.formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
django视图
import json
class MyView(View):
def post(self, request):
body = json.loads(request.body)
# Do stuff
但是,json
模块抱怨:
TypeError: the JSON object must be str, not 'bytes'
为什么数据不是作为JSON发送的,我应该如何最好地将有效负载转换为Python对象?
答案 0 :(得分:3)
将Content-type
更改为application/json
headers: {
'Content-Type': 'application/json'
}
值得注意的是,默认的角度$http POST
行为是将数据作为JSON发送。因此,另一种策略可能是从您的headers
来电中删除$http
。
此外,您可能希望使用simplejson
而不是json
以下解释来自this question:
json
是simplejson
,添加到python stdlib中。但是由于在{2.6}中添加了json
,simplejson
具有处理更多Python版本(2.4 +)的优势。
simplejson
也比Python更频繁地更新,因此如果您需要(或想要)最新版本,最好尽可能使用simplejson
。