Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

vue.js - Handling single page application url and django url

I have a single page application created in Vue.js that utilizes the HTML5 History Mode for routing, and the html file is served with Django.

The urls.py of django is like so:

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

And views.home:

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

Consider the following scenario:

  1. User visits the home page (i.e., /)

Since, the home page responds with required index.html for the Single page Vuejs app, it works like its supposed to.

  1. From there the user navigates to the about page (i.e., /username/12).

Its still working fine, as its navigating with the Vue router.

  1. Now, the user refreshes the page.

Since there's no /username/12 in the urls.py patterns, it will show Page not found (404).

Now, I could provide another pattern in urls.py to catch all pattern in the last order as this:

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

But other urls like the media or static urls will also point to the same catch all pattern regex. How can I solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have a similar problem.

How can I use vue-router and django rest framework the same time?

This is my solution to this problem. Hope it helps you.

Expected results:

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

and I try this and it works!

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")),
]

The order is important, url(r'^.*$', TemplateView.as_view(template_name="index.html")), is the last one

and this is my vue router

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

My project on GitHub


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...