programing

한 페이지 어플리케이션 URL 및 django URL 처리

kingscode 2022. 7. 14. 22:29
반응형

한 페이지 어플리케이션 URL 및 django URL 처리

라우팅에 HTML5 이력 모드를 사용하는 Vue.js에서 작성된 단일 페이지 어플리케이션이 있으며 html 파일은 Django와 함께 제공됩니다.

django의 urls.py은 다음과 같습니다.

urlpatterns = [
    url(r'^$', views.home),
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
]

그리고.:

def home(request):
    return render(request, 'index.html')

다음 시나리오를 고려합니다.

  1. 사용자는 홈 페이지를 방문합니다(즉,/)

홈 페이지는 싱글 페이지 Vuejs 앱에 필요한 index.html로 응답하므로 정상적으로 동작합니다.

  1. 여기서 사용자는 About 페이지로 이동합니다(즉,/username/12).

Vue 라우터를 사용한 네비게이션으로 정상적으로 동작하고 있습니다.

  1. 이것으로, 유저는 페이지를 갱신합니다.

없기 때문에/username/12urls.py 패턴에서는 "Page not found"(404)라고 표시됩니다.

urls.py에 다른 패턴을 입력하여 다음과 같이 마지막 순서로 모든 패턴을 캡처할 수 있습니다.

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^.*$', views.home),
]

그러나 미디어나 정적 URL과 같은 다른 URL도 동일한 catch all pattern regex를 가리킵니다.어떻게 하면 이 문제를 해결할 수 있을까요?

저도 비슷한 문제가 있어요.

vue-router와 django rest 프레임워크를 동시에 사용하려면 어떻게 해야 합니까?

이것이 이 문제에 대한 나의 해결책이다.도움이 되길 바랍니다.

예상 결과:

http://127.0.0.1:8000/       <-- TeamplateView index.html using vue
http://127.0.0.1:8000/course <-- vue-router
http://127.0.0.1:8000/api    <-- rest framework
http://127.0.0.1:8000/admin  <-- django admin

이걸 시도해보니 효과가 있어!

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/', include(router.urls)),
    url(r'^.*$', TemplateView.as_view(template_name="index.html")),
]

순서는 중요하지만url(r'^.*$', TemplateView.as_view(template_name="index.html")),마지막이다

그리고 이것은 나의 vue 라우터입니다.

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [{
      path: '/courses',
      component: CourseSet
    }, {
      path: '/',
      component: hello
    }]
})

GitHub에 대한 내 프로젝트

"단일 페이지"를 언급했으므로:

  1. 서버는 1페이지만 전송하도록 되어 있습니다.index.html(또는 다른 이름으로 불러주세요)

  2. 서버와 웹 애플리케이션(프런트 엔드) 코드는 API 호출을 통해 통신하므로 서버가 리소스를 제공하고 웹 앱이 해당 리소스를 사용합니다.

  3. 리소스가 부족한 경우에도 서버는 별도의 페이지로 응답하지 않고 웹 앱에서 사용할 수 있는 메시지로 응답해야 합니다.

라우팅에 HTML5 이력 모드를 사용하는 단일 페이지 애플리케이션을 Vue.js로 작성했습니다.

vue-router를 사용하고 계신 것 같습니다.vue-router는 싱글 페이지 앱을 풀 기능의 멀티 페이지 애플리케이션으로 시뮬레이트하고 있습니다.


이것저것 살펴보고 싶을 수도 있지만, 위의 내용은 한 페이지 응용프로그램에 적용됩니다.


url 패턴을 공유했습니다.

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^api-token-auth/', obtain_jwt_token),
  url(r'^.*$', views.home),
]

그러나 미디어나 정적 URL과 같은 다른 URL도 동일한 catch all pattern regex를 가리킵니다.어떻게 하면 이 문제를 해결할 수 있을까요?

  1. 할 수 「경로」가 아닌 다른 입니다.'/'상술한 바와 같이/app.

    urlpatterns = [
      url(r'^admin/', admin.site.urls),
      url(r'^api-token-auth/', obtain_jwt_token),
      url(r'^.*$/app', views.home),
    ]
    

    router.filename 파일:

    new Router({
      mode: 'History',
      base: '/app'
      routes: [
        {
          path: '/',
          name: 'name',
          component: ComponentName
        }
      ]
    })
    
  2. 또는 다음과 같은 URL에 의해 제공되는 목적 앞에 접두사를 붙입니다.

    urlpatterns = [
      url(r'^api/admin/', admin.site.urls),
      url(r'^api/api-token-auth/', obtain_jwt_token),
      url(r'^.*$', views.home),
      url(r'^.*$/assets', your-static-assets) 
    ]
    

다음과 같이 Django 2.x에서 VueJS 라우터 활성화 이력 모드를 사용하고 있습니다.

에서 urls.py으로 합니다.repathURL을 사용하다

# urls.py

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

urlpatterns = [
    path('', TemplateView.as_view(template_name="application.html"), name="app", ),
    # ... rest of your urls
]

urlpatterns += [
    re_path('^.*$', TemplateView.as_view(template_name="application.html")),
]

이제 이력 모드가 원활하게 작동합니다!

http://sample.com/#/users/login/

결과:

http://sample.com/users/login/

룩어헤드으로 안에 있는 것은 이든 상관없습니다.기본적으로 안에 있는 모든 것입니다.(?!ignore1|ignore2)시됩니니다다

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^(?!admin|api-token-auth|static).*$', views.home),
]

주의: 다음을 포함하지 않도록 했습니다.admin ★★★★★★★★★★★★★★★★★」api-token-auth 네거티브 룩어헤드(Negative Look-Ahead)로 하는 경로는 .adminviews.home내가 이해한 바로는 왜 장고가 먼저 이전의 것과 일치해야 하는지 모르겠다.

index.html은 스태틱이 아닌 뷰에서 제공되기 때문에 템플릿(동적 페이지)이기 때문에 조금 이상합니다.

프로덕션에서는 반드시 nginx 또는 apache를 사용하여 유사한 방식으로 정적 컨텐츠를 처리합니다.

개발을 위해 다음과 같이 하겠습니다.

from django.contrib.staticfiles.views import serve

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token),
]

# Serve your static media (regex matches *.*)
if settings.DEBUG:
    urlpatterns.append(url(r'(?P<path>.*\..*)$', serve))

# Serve your single page app in every other case
urlpatterns.append(url(r'^.*$', views.home))

위의 @billi의 답변은 어느 정도 유효합니다.문제는 SPA에서 Vue <router-view> <router-link> 시스템을 사용해야 한다는 것입니다.단, router.diag는 Vue 컴포넌트에 경로를 매핑합니다.경로 중 일부는 Django urls.py 경유로 Django 뷰에 접속합니다.예를 들어 Vue 라우터의 네비게이션에서 /api/place로 이동하면 공백 페이지가 되지만 새로고침되면 Django로 올바르게 해결됩니다.

아이디어?

urls.py

urlpatterns = [
    # Django
    path('admin', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls')),
    url(r'^api/places$', views.PlaceList.as_view()),

    # catchall to Vue single page app
    url(r'^.*$', TemplateView.as_view(template_name='myapp/spa.html'), name='home'),
]

router.displaces

export default new Router({
  mode: 'history',
  routes: [
    {path: '/search', component: Search},
    {path: '/about', component: About},
    {path: '/', component: Home},
    {path: '/api/places', }
  ]
})

App.vue

<template>
  <div id="app">
    <div>
    <router-link to="/search">Search</router-link> ::
    <router-link to="/about">About</router-link>
    <router-link to="/">Home</router-link> ::
    <router-link to="/api/places">Place API</router-link> ::
  </div>
  <router-view></router-view>
  </div>
</template>

아직도 해결책을 찾는 사람이 있을지 모르겠네요.저는 완전히 스탠드어론 방식으로 장고레스트 API와 Vue 프런트를 구축합니다.그리고 dist폴더 아이템을 Django의 정적 파일에 넣고 gunicorn과 NGINX를 통해 서버를 하려고 했을 때 스파가 작동하지 않았습니다.마침내 이것을 해냈는데 놀랍게도 효과가 있었다.

기본적으로는

오류 페이지를 Vue의 index.html전송합니다.

NGINX 설정은 다음과 같습니다.

location /static/ {
    root /root/bdn/bdn/server/;
}

location /media/ {
    root /root/bdn/bdn/server/;
}

location ^~ /admin/ { # Define routes to be directed to backend as proxy
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://unix:/run/gunicorn.sock;
}

location ^~ /api/ { # Define routes to be directed to backend as proxy
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://unix:/run/gunicorn.sock;
}

location ^~ /api-auth/ {
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://unix:/run/gunicorn.sock;
}

location ^~ /{
    root /root/bdn/bdn/server/templates/;
    index index.html;
}

error_page 404 /;  # THIS IS WHAT IT CAME DOWN TO AFTER HOURS AND HOURS OF SEARCHING

언급URL : https://stackoverflow.com/questions/42864641/handling-single-page-application-url-and-django-url

반응형