POST请求上的JSON解析错误

问题描述:

我使用了django-cors-headers,并对其进行配置。POST请求上的JSON解析错误

后端: Django的1.11 + Django的其余框架3.6.3

settings.py

ALLOWED_HOSTS = ['*'] 
MIDDLEWARE = [ 
'django.middleware.security.SecurityMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'corsheaders.middleware.CorsMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware', 
] 
CORS_ORIGIN_ALLOW_ALL = True 

蟒manage.py的runserver 192.168.1.111:8000

前端:

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("button").click(function(){ 
     $.ajax({url: "http://192.168.1.111:8000/api/user/forgot_password/", 
     type: "post", 
     data: {"email": "[email protected]"}, 
     headers:{"Content-Type":"application/json"}, 
     success: function(result){ 
      $("#div1").html(result); 
     }}); 
    }); 
}); 
</script> 
</head> 
<body> 

<div id="div1"></div> 

<button>Forget Password</button> 

</body> 
</html> 

获取400个POST请求和响应的响应se内容

{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} 

但是,当我从邮递员调用这个API它的工作正常。我该如何解决这个问题?

您在JavaScript中的错误,你的Ajax POST请求的格式不好,你不字符串化数据

data: JSON.stringify("{"email": "[email protected]"}") 

反而增加头部手动你可以使用

contentType: "application/json" 

$.ajax({ 
    url: "http://192.168.1.111:8000/api/user/forgot_password/", 
    type: "POST", 
    data: JSON.stringify({ "email": "[email protected]" }), 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    success: function (result) { 
     $("#div1").html(result); 
    }, 
    error: function (xhr, textStatus, errorThrown) { 
    } 
}); 

试试这个一。

你可以尝试发布前你的JSON转换为字符串 -

JSON.stringify({"email": "[email protected]"}) 
+1

请看看https://*.com/help/how-to-answer。尝试在答案中提供一些细节,例如为什么它不工作,他们应该尝试什么。 – majita