为什么Javascript请求会出现“ CSRF令牌丢失或不正确”错误

问题描述 投票:0回答:1

我试图在单击按钮时用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")
javascript python django ajax csrf
1个回答
0
投票

您必须在每个JavaScript请求中发送CSRF令牌:https://docs.djangoproject.com/en/2.2/ref/csrf/#ajax

© www.soinside.com 2019 - 2024. All rights reserved.