Django==3.2.3
django-cors-headers==3.7.0
观看次数
class LoginView(FormView):
form_class = LoginForm
template_name = "users/login.html"
def form_valid(self, form):
...
super().post(self.request)
return
模板
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
js
$.ajax({
type: 'POST',
url: "http://localhost:8000/users/login/",
processData: false,
contentType: false,
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRFToken', $('[name=csrfmiddlewaretoken]').val());
},
data: {
...
},
})
我查看 network
- 标题中的标记与表单中的标记相同。
还安装了corsheaders
INSTALLED_APPS = [
....
"corsheaders",
....
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
....
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ["http://127.0.0.1:8000"]
CORS_ALLOW_METHODS = ["*"]
CORS_ALLOW_HEADERS = ["*"]