Получение простого файла кода Js в ответе Axios GET в ответ при попытке получить данные tp Использование DRF

У меня возникла эта проблема, когда я делал запрос Get из моего React Frontend в Drf Backend. Предполагалось, что он получит сведения о пользователе и установит его в состояние при отправке с помощью Redux, но ответ от бэкэнда - это файл или индекс кода Pure Js. .html, который мы предполагаем иметь в папке сборки при запуске React With Django.

export const load_user = () => async dispatch => {
    if (localStorage.getItem('access')) {
        console.log('True')
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `JWT ${localStorage.getItem('access')}`,
                
            }
        };

        try {
            const res = await axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config);
            const user_type = res.data.type_of_user.toLowerCase()
            const id = res.data.id
            
            const res1 = await axios.get(`${process.env.REACT_APP_API_URL}/app/${user_type}/${id}`, config)
            console.log(res1.data)
            dispatch({
                type: USER_LOADED_SUCCESS,
                payload: res1.data
            });
        } catch (err) {
            dispatch({
                type: USER_LOADED_FAIL
            });
        }
    }
    else {
        dispatch({
            type: USER_LOADED_FAIL
        });
    }
};

Вот настройка представления шаблона URLs.py для Django для загрузки файла сборки index.html.

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from app.views import index
urlpatterns=[
    path('admin/', admin.site.urls),
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.jwt')),
    path('app/', include('app.urls')),
    path("", index )

]
urlpatterns+=[re_path("", TemplateView.as_view(template_name='index.html'))]

вот urls.py приложения

from django.urls import path
from .views import PatientView, DoctorView, VitalView, UserView, send_mail_to_doctor, VitalsDataView,user_list

from django.views.decorators.csrf import csrf_exempt

urlpatterns=[

    path('patient/<int:id>/',PatientView.as_view(), name="patient"),
    path('doctor/<int:did>/',DoctorView.as_view(), name="doctor"),
    path('vital/<int:pid>/',VitalView.as_view(), name="vital"),
    path('vitals/<int:pid>/',VitalsDataView.as_view(), name="vitalData"),
    path('users/',UserView.as_view(), name="UserData"),
    path('send_mail_to_doctor/', csrf_exempt(send_mail_to_doctor), name="send_mail_to_doctor"),
    # URL form "/api/users/1"
    path('api/users/<int:pk>', user_list, name='user-detail'),      # GET request for user with id
    path('api/users/', user_list, name='user-list')
]

Файл кода, который я получаю, когда я делаю запрос,

<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"/><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"/><link rel="manifest" href="/manifest.json"/><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"><title>React App</title><link href="/static/css/main.3ab95596.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script><script>!function(e){function r(r){for(var n,f,l=r[0],i=r[1],a=r[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,l=1;l<t.length;l++){var i=t[l];0!==o[i]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var l=this.webpackJsonpfrontend=this.webpackJsonpfrontend||[],i=l.push.bind(l);l.push=r,l=l.slice();for(var a=0;a<l.length;a++)r(l[a]);var p=i;t()}([])</script><script src="/static/js/2.fbf2c2fe.chunk.js"></script><script src="/static/js/main.d3c07340.chunk.js"></script></body></html>

Вместо приведенного выше кода я должен был получить информацию о пользователе. Любая помощь высоко ценится! Спасибо


person 5h4d0w5    schedule 26.11.2020    source источник


Ответы (1)


Что ж, спасибо, ребята, так как он остался без ответа, я копнул глубже и получил ответ сам. То, что я делал ранее, заключалось в том, что я использовал TemplateView для рендеринга файла index.html кода реакции, который каким-то образом конфликтовал с serializers.py, и я получил этот файл кода в ответ, теперь я изменил структуру React Frontend и использую приложение Django для обслуживания index.html React и его index.js в качестве статической папки в django. Я настоятельно рекомендую посмотреть видео Full Stack React от Traversy Media на Youtube, чтобы подготовить ту же структуру › Еще раз спасибо :)

person 5h4d0w5    schedule 07.12.2020