我试图在单击按钮时用Javascript创建请求,但收到错误Forbidden (CSRF token missing or incorrect.)
。
我在HTML模板中添加了{% csrf_token %}
:
<form action="/cart" method="POST">
{% csrf_token %}
<button type="button" id="ordered">Place Order</button>
</form>
但是不确定是否必须将其包含在我的Javascript请求中:
const request = new XMLHttpRequest();
request.open("POST", "/cart");
// send request
let data = new FormData();
items = localStorage.getItem(user + "items")
total = localStorage.getItem(user + "price")
data.append("items", items)
data.append("total", total)
request.send(data);
在我的views.py
中:
def cart(request):
if request.method == "POST":
data = request.get_json()
print(f"{data}")
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "cart.html")
答案 0 :(得分:0)
您必须在每个JavaScript请求中发送CSRF令牌:https://docs.djangoproject.com/en/2.2/ref/csrf/#ajax
答案 1 :(得分:0)
要摆脱此错误,只需将CSRF令牌附加到您的json数据或将其添加到标头中,如下所示。
...
headers: {'X-CSRFToken': '{{ csrf_token }}'}
...
或
...
headers: [{name: 'X-CSRFToken', value: csrfToken.value}],
...