Unable to make a POST fetch request using Django (with React/JS)

How to send data using a POST fetch request from React/JS to a Django server? I'm able to make a GET request, so the servers working in that regard.

The error I get from the terminal is:

[0] Forbidden (Origin checking failed - http://localhost:3000 does not match any trusted origins.): /hello/
[0] [04/Feb/2023 08:31:02] "POST /hello/ HTTP/1.1" 403 2569

The error I get from browser console is:

Form.jsx:47
       POST http://localhost:8000/hello/ 403 (Forbidden)

First of all I installed npm install js-cookie and imported Cookies

Fetch request

import Cookies from 'js-cookie'

        ...

        const response = await fetch('http://localhost:8000/hello/', {
            method: 'POST',
            headers: {
                "X-CSRFToken": Cookies.get('csrftoken'),
                "Accept": "application/json",
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                some_data: 'some_value'
            })
        });
        const data = await response.text();
        console.log(data);

urls.py

urlpatterns = [
    path('hello/', views.hello_world, name='hello_world'),
]

views.py

def hello_world(request):
    if request.method == 'POST':
        # do something with the data posted
        data = request.POST
        # return a JSON response
        return HttpResponse("Success: ")
    return HttpResponse("Error: ")

settings.py

INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

# Tested using a combination of:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
    "http://localhost:3000",
]
CORS_ALLOW_METHODS = ['POST']
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
CORS_ALLOW_METHODS = (
    'GET',
    'POST',
    'OPTIONS',
)
CORS_ALLOW_CREDENTIALS = True

I also get this error/.text() response from:

const data = await response.text();
console.log(data);

Error/.text() response

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <title>403 Forbidden</title>
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; background:#eee; color:#000; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; margin-bottom:.4em; }
    h1 span { font-size:60%; color:#666; font-weight:normal; }
    #info { background:#f6f6f6; }
    #info ul { margin: 0.5em 4em; }
    #info p, #summary p { padding-top:10px; }
    #summary { background: #ffc; }
    #explanation { background:#eee; border-bottom: 0px none; }
  </style>
</head>
<body>
<div id="summary">
  <h1>Forbidden <span>(403)</span></h1>
  <p>CSRF verification failed. Request aborted.</p>


</div>

<div id="info">
  <h2>Help</h2>
    
    <p>Reason given for failure:</p>
    <pre>
    Origin checking failed - http://localhost:3000 does not match any trusted origins.
    </pre>
    

  <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  <a
  href="https://docs.djangoproject.com/en/4.1/ref/csrf/">Django’s
  CSRF mechanism</a> has not been used correctly.  For POST forms, you need to
  ensure:</p>

  <ul>
    <li>Your browser is accepting cookies.</li>

    <li>The view function passes a <code>request</code> to the template’s <a
    href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>
    method.</li>

    <li>In the template, there is a <code>{% csrf_token
    %}</code> template tag inside each POST form that
    targets an internal URL.</li>

    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
    <code>csrf_protect</code> on any views that use the <code>csrf_token</code>
    template tag, as well as those that accept the POST data.</li>

    <li>The form has a valid CSRF token. After logging in in another browser
    tab or hitting the back button after a login, you may need to reload the
    page with the form, because the token is rotated after a login.</li>
  </ul>

  <p>You’re seeing the help section of this page because you have <code>DEBUG =
  True</code> in your Django settings file. Change that to <code>False</code>,
  and only the initial error message will be displayed.  </p>

  <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>

</body>
</html>

In settings.py you have to add http://localhost:3000 to the list of trusted origins for unsafe requests (e.g. POST).

add this to your settings.py :

CSRF_TRUSTED_ORIGINS = [
    'http://localhost:3000'
],

I had same issue, but when I log out of admin account this error disappears... I can't exaplin why. but try to logout and retry.

Back to Top