Axios Error. When Connect to api, It makes network error [closed]

  • Environment: Mac OS m2.

  • Framework : Django, Vue.

  • IDE : PyCharm.

  • Library :

opencv-python==4.6.0.66. mediapipe-silicon==0.8.10.1.
keras==2.9.0. keras-tuner==1.1.3. tensorflow-macos==2.15.1.
numpy==1.23.3. scikit-learn==1.1.2. pandas==1.4.3.
matplotlib==3.6.0. seaborn==0.12.0. yellowbrick==1.5.
Django==4.2.13. djangorestframework==3.14.0.
django-cors-headers==3.13.0. django-extensions==3.2.1.
protobuf==3.20.


Hello, Hi, I'm studying with using someone else's repository regarding pose detection.
I haven't been able to fix the issue for weeks regarding the axios network error.

- Problem

Error:  
m
code: "ERR_NETWORK"
config: {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}adapter: (3) ['xhr', 'http', 'fetch']data: FormData {}env: {FormData: ƒ, Blob: ƒ}headers: oe {Accept: 'application/json, text/plain, */*', Content-Type: undefined}maxBodyLength: -1maxContentLength: -1method: "post"timeout: 0transformRequest: [ƒ]transformResponse: [ƒ]transitional: {silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false}url: "http://127.0.0.1/api/video/upload?type=bicep_curl"validateStatus: ƒ (t)xsrfCookieName: "XSRF-TOKEN"xsrfHeaderName: "X-XSRF-TOKEN"[[Prototype]]: Object
message: "Network Error"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}onabort: ƒ ()onerror: ƒ ()onload: nullonloadend: ƒ p()onloadstart: nullonprogress: nullonreadystatechange: nullontimeout: ƒ ()readyState: 4response: ""responseText: ""responseType: ""responseURL: ""responseXML: nullstatus: 0statusText: ""timeout: 0upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}withCredentials: false
[[Prototype]]: XMLHttpRequeststack: "AxiosError: Network Error\n    at l.onerror (http://127.0.0.1:8000/static/assets/js/VideoStreaming-c1cd5834.js:3:6205)\n    at Z.request (http://127.0.0.1:8000/static/assets/js/VideoStreaming-c1cd5834.js:5:1946)\n    at async o (http://127.0.0.1:8000/static/assets/js/VideoStreaming-c1cd5834.js:6:9733)"
[[Prototype]]: Error

The Server is running normally, and there is no error in terminal. then I connect to web page successfully at
http://127.0.0.1:8000/.

But a network error occurs when I press the 'process' button that performs the core function.
The core fuction connect to url like
'http://127.0.0.1/api/video/upload?type=bicep_curl'.
and maybe this makes the network error.

I connect into
http://127.0.0.1:8000/video
Then if I click the button, the connection route is below.

1. root/web/client/src/views/VideoStream.vue - button

<button class="process-btn" @click="uploadToServer">
                <span>Process!</span>
            </button>

2. root/web/client/src/views/VideoStream.vue - def uploadToServer

const uploadToServer = async () => {
    if (!submitData.value.videoFile) {
        alert("No video selected");
        return;
    }

    if (!submitData.value.exerciseType) {
        alert("No exercise type selected");
        return;
    }

    processedData.value = null;
    try {
        isProcessing.value = true;
        const { data } = await axios.post(
            `${apiUrl}/api/video/upload?type=${submitData.value.exerciseType}`,
            { file: submitData.value.videoFile },
            {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            }
        );
        processedData.value = data;
    } catch (e) {
        console.error("Error: ", e);
    } finally {
        isProcessing.value = false;
    }
};

3. root/web/server/api/urls.py - urlpatterns

from django.urls import path, include
from . import views

urlpatterns = [
    path("", views.api, name="api"),
    path("video/", include("stream_video.urls")),
]

4. root/web/server/api/views.py - def api

from rest_framework.decorators import api_view
from rest_framework.response import Response
from datetime import datetime


@api_view(["GET"])
def api(request):
    urls = {"name": "Quoc Bao", "dob": "10/10/2000", "time": datetime.now()}
    return Response(urls)

5. root/web/server/stream_video/urls.py - urlpattern

from django.urls import path
from . import views

urlpatterns = [
    path("stream", views.stream_video, name="stream"),
    path("upload", views.upload_video, name="upload"),
]

6. root/web/server/stream_video/views.py - def upload_video

@api_view(["POST"])
@parser_classes([MultiPartParser])
def upload_video(request):
    exercise_type = request.GET.get("type")
    if not exercise_type:
        return JsonResponse(
            status=status.HTTP_400_BAD_REQUEST,
            data={
                "message": "Exercise type has not given",
            },
        )

    try:
        if request.method == "POST":
            video = request.FILES["file"]

            # Convert any video to .mp4
            now = datetime.now()
            now = int(now.strftime("%Y%m%d%H%M%S"))
            name_to_save = f"video_{now}.mp4"

            # Process and Saved Video
            results, *other_data = exercise_detection(
                video_file_path=video.temporary_file_path(),
                video_name_to_save=name_to_save,
                exercise_type=exercise_type,
                rescale_percent=40,
            )

            # Convert images path to URL
            host = request.build_absolute_uri("/")
            for index, error in enumerate(results):
                if error["frame"]:
                    results[index]["frame"] = host + f"static/images/{error['frame']}"

            response_data = {
                "type": exercise_type,
                "processed": True,
                "file_name": name_to_save,
                "details": results,
            }

            # Handle others data
            if exercise_type in ["squat", "lunge", "bicep_curl"]:
                response_data["counter"] = other_data[0]

            return JsonResponse(
                status=status.HTTP_200_OK,
                data=response_data,
            )

    except Exception as e:
        print(f"Error Video Processing: {e}")
        # traceback.print_exc()

        return JsonResponse(
            status=status.HTTP_400_BAD_REQUEST,
            data={
                "error": f"Error: {e}",
            },
        )

I mailed about the error to original author of repository, but didn't get answer.

I looked it up a lot, and search it, then I found maybe it's a CORS-related problem,
and the answers said me that the "If you write about the corsheader in settings, then the problem will solve".
but that part has already been written.

- I already write about CORS in settings.py

ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Install libraries
    "rest_framework",
    "corsheaders",
    "django_extensions",
    # My Apps
    "api.apps.ApiConfig",
    "stream_video.apps.StreamVideoConfig",
]

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

CORS_ALLOW_ALL_ORIGINS = True

This is my guess, While going through the code, I found that only 'corsheaders' are underlined on the IDE.

I suppose maybe there's something wrong, so IDE don't recognize the corsheads and just judge it as a simple 'typo'.


Is there anyone who can help with this?
It's urgent because it's related to my university graduation work.
You can check the specific code in.
https://github.com/CreamMeatball/AI_SportFeedback.
and you can install requirements by 'requirements-mac-edit.txt' in mac.
Thank you.

Back to Top