Search code examples
pythondjangoajaxazure

error in the application's ajax request in an azure app


I have an app in python-django and on localhost everything works normally. I make ajax requests to Python correctly, however it doesn't work in the Azure application, follow the example code of how I make a request:

 $.ajax({
                url: '/PlanEx/DCC/GerarTabelaAnova',
                data: formData,
                type: 'POST',

Furthermore, my gateway app constantly times out


Solution

  • I tried deploying a simple Django project, which includes an AJAX POST request, to Azure App Service without any issues.

    This is my project structure

    ajax_project/
    ├── ajax_example/
    │   ├── migrations/
    │   ├── templates/
    │   │   └── ajax_example_post.html
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── urls.py                 
    │   └── views.py
    ├── ajax_project/
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── db.sqlite3
    ├── manage.py
    └── requirements.txt
    

    ajax_example/views.py:

    from django.http import JsonResponse
    from django.shortcuts import render
    from django.views.decorators.csrf import csrf_exempt 
    
    def ajax_post_page(request):
        return render(request, 'ajax_example_post.html')
    
    @csrf_exempt
    def ajax_post_view(request):
        if request.method == 'POST':
            data = request.POST.get('data', '')
            
            response_data = {'received_data': data}
            
            return JsonResponse(response_data)
        else:
            return JsonResponse({'error': 'Only POST requests are allowed'})
    

    ajax_example/urls.py:

    from  django.urls  import  path
    from .views  import  ajax_post_view, ajax_post_page
    urlpatterns  = [
    path('ajax-post/', ajax_post_view, name='ajax_post_view'),
    path('ajax-post-page/', ajax_post_page, name='ajax_post_page'),
    ]
    

    ajax_example_post.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AJAX POST Example</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
        <button id="send-post">Send POST Request</button>
        <script>
            $(document).ready(function() {
                $('#send-post').click(function() {
                    var dataToSend = {'key': 'value'};  // JSON data to send
                    var csrftoken = getCookie('csrftoken'); 
                    $.ajax({
                        url: '/ajax/ajax-post/',
                        type: 'POST',
                        headers: {
                            'X-CSRFToken': csrftoken 
                        },
                        data: dataToSend,
                        success: function(response) {
                            console.log('Response:', response);
                        },
                        error: function(xhr, status, error) {
                            console.error('Error:', error);
                        }
                    });
                });
            });
    
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) === (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        </script>
    </body>
    </html>
    

    ajax_project/urls.py:

    from  django.urls  import  path, include
    from  ajax_example.views  import  ajax_post_page 
    urlpatterns  = [
    path('', ajax_post_page), 
    path('ajax/', include('ajax_example.urls')),
    ]
    

    Settings.py:

    from pathlib import Path
    BASE_DIR = Path(__file__).resolve().parent.parent
    SECRET_KEY = 'django-insecure-lmn9zwrj2x99-*y$%l-4dl%*e)dyy=g#d%-_0ee&mq-#@)cl4)'
    DEBUG = False
    ALLOWED_HOSTS =['127.0.0.1', 'sdjangoajax.azurewebsites.net'
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    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',
    ]
    ROOT_URLCONF = 'ajax_project.urls'
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / 'ajax_example' / 'templates'],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'ajax_project.wsgi.application'
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    LANGUAGE_CODE = 'en-us'
    TIME_ZONE = 'UTC
    USE_I18N = True
    USE_TZ = True
    STATIC_URL = 'static/'
    DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
    

    Create a requirements.txt file before deploying your app to azure app service

    To generate a requirements.txt file, you can use the following command in your terminal.

    pip freeze > requirements.txt
    

    Local output:

    enter image description here

    Here's the output after deployment:

    enter image description here