2017-07-29 123 views
0

我使用了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它的工作正常。我該如何解決這個問題?

回答

2

您在JavaScript中的錯誤,你的Ajax POST請求的格式不好,你不字符串化數據

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

反而增加頭部手動你可以使用

contentType: "application/json" 
2
$.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) { 
    } 
}); 

試試這個一。

1

你可以嘗試發佈前你的JSON轉換爲字符串 -

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

請看看https://stackoverflow.com/help/how-to-answer。嘗試在答案中提供一些細節,例如爲什麼它不工作,他們應該嘗試什麼。 – majita