reactjs csrftoken在React呈现的形式中为null

yhuiod9q  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(149)

我在前端使用纯React,后端使用Django。
我使用React来渲染表单&而不是使用Django表单。
我目前无法从React前端(http://localhost:3001/)向Django后端(http://127.0.0.1:8000)发出POST请求,因为Forbidden (CSRF cookie not set.): /createListing错误。
这就是我的POST请求代码的样子

async function getCSRFToken() {
    const response = await fetch("http://127.0.0.1:8000/getCSRFToken");
    const jsonResponse = await response.json();
    console.log("CSRFToken: ", jsonResponse["token"]);
    return jsonResponse["token"];
  }

async function createListing(listing) {
    let csrftoken = getCSRFToken();
    const response = await fetch(
      "http://127.0.0.1:8000/createListing/",
      {
        method: "POST",
        body: JSON.stringify(listing),
        headers: {
          "Content-Type": "application/json",
          "X-CSRFToken": csrftoken
        },
      }
    );
    const data = await response.json();
    return data;
}

这是我的Django API端点

def createListing(request):
    # Creating a new Listing must be via POST
    if request.method != "POST":
        return JsonResponse({"error": "POST request required."}, status=400)

    # Load Listing JSON from request body
    data = json.loads(request.body)

    # Retrieve Listing details
    name = data.get("name")
    description = data.get("description")
    rating = data.get("rating")
    price_nightly = data.get("price_nightly")

    # ... data manipulation

    return JsonResponse({"message": "Listing created successfully."}, status=201)

我还创建了一个Django视图来从Django检索CSRF令牌
urls.py

path("getCSRFToken", views.getCSRFToken, name="getToken")

views.py

from django.middleware.csrf import get_token

def getCSRFToken(request):
    token = get_token(request)
    return JsonResponse({"token": token}, status=200)

我在看这个answer
将CSRF令牌记录到控制台,我可以看到CSRF令牌正在生成,但我仍然得到相同的Forbidden (CSRF cookie not set.): /createListing错误。

// CSRF Token logged to console
KCr2laoLVmK9amwt0uBUKJze72T2qwLdbRbgPwOQdsKFGKIB2G5qA0940UsL2Bt0

我能够生成CSRF令牌,但是将其传递到POST请求的头中似乎不起作用。我是不是漏掉了什么?

olmpazwi

olmpazwi1#

在你的Django的view中做这个小修改再试一次。

#first you need to import this
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt # add this decorator
def createListing(request):
    # Creating a new Listing must be via POST
    if request.method != "POST":
        return JsonResponse({"error": "POST request required."}, status=400)

    # Load Listing JSON from request body
    data = json.loads(request.body)

    # Retrieve Listing details
    name = data.get("name")
    description = data.get("description")
    rating = data.get("rating")
    price_nightly = data.get("price_nightly")

    # ... data manipulation

    return JsonResponse({"message": "Listing created successfully."}, status=201)

相关问题