我使用了django-cors-headers,并对其进行了配置。
后端: Django 1.11 + django-rest-framework 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
python 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": "nikhil.29bagul@gmail.com"},
headers:{"Content-Type":"application/json"},
success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"></div>
<button>Forget Password</button>
</body>
</html>
获取POST请求和响应内容的400响应
{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}
但是当我从邮递员那里调用这个API时,它的工作正常。我该如何解决这个问题?
答案 0 :(得分:3)
Imports System.Web
Imports System.Text
Imports System.Web.HttpContext
尝试这个。
答案 1 :(得分:2)
你有javascript错误,你的Ajax POST请求格式错误,因为你没有字符串化数据
data: JSON.stringify("{"email": "nikhil.29bagul@gmail.com"}")
而是手动添加标题,您可以使用
contentType: "application/json"
答案 2 :(得分:1)
您可以尝试在发布前将JSON转换为字符串 -
JSON.stringify({"email": "nikhil.29bagul@gmail.com"})