[Python] POST 405 (Method Not Allowed) Django REST [closed]

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    The problem is when sending a post request from the client to the django server. Both the client and the server are deployed locally. I've double-checked where the problem might be many times, so I'm attaching the code from the views and settings file.

    javascript code

    fetch('http://127.0.0.1:8000/products/', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(data => console.log(data.basket))
    .catch(error => console.error('Basket get error', error));


    python code

    views:

    @csrf_exempt
    def get_all_products(request):
    if request.method == 'POST':

    try:
    data = json.loads(request.body)
    print(data)

    except Exception as e:
    return JsonResponse({'error': str(e)}, status=400)

    return JsonResponse({'error': 'Invalid request method'}, status=405)


    settings:

    ALLOWED_HOSTS = ['localhost', '127.0.0.1']

    # Application definition

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mini_app',
    'corsheaders'
    ]

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

    ]

    CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'DELETE'
    ]

    CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:5500',
    'http://localhost:5500'
    ]


    output in the python django console:

    Method Not Allowed: /products/
    [05/Apr/2025 13:05:54] "POST /products/ HTTP/1.1" 405 35


    output in the browser console

    POST http://127.0.0.1:8000/products/ 405 (Method Not Allowed)

    Continue reading...

Compartilhe esta Página