问题描述
我在Vue.js中创建了一个单页应用程序,该应用程序使用HTML5历史记录模式进行路由,并且html文件与Django一起提供。
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.
django的> urls.py 就像这样:
urlpatterns = [
url(r'^$', views.home),
url(r'^admin/', admin.site.urls),
url(r'^api-token-auth/', obtain_jwt_token),
]
和 views.home :
def home(request):
return render(request, 'index.html')
请考虑以下情形:
- 用户访问主页(即
/
)
- User visits the home page (i.e.,
/
)
自此以来,主页以所需的索引进行响应.html用于单页Vuejs应用程序,它的工作原理与预期的一样。
Since, the home page responds with required index.html for the Single page Vuejs app, it works like its supposed to.
- 从此处用户导航至关于页面(即
/ username / 12
)。
- From there the user navigates to the about page (i.e.,
/username/12
).
它
- 现在,用户刷新页面。 >
由于 urls.py中没有 / username / 12
strong>模式,它将显示未找到页面(404)。
Since there's no /username/12
in the urls.py patterns, it will show Page not found (404).
现在,我可以在 urls.py中提供另一种模式按以下顺序捕获所有模式:
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?
推荐答案
如何同时使用vue-router和django rest
框架 ?
How can I use vue-router and django rest framework the same time?
这是我对这个问题的解决方案。希望对您有帮助。
This is my solution to this problem. Hope it helps you.
预期结果:
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")),
]
这是我的Vue路由器
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [{
path: '/courses',
component: CourseSet
}, {
path: '/',
component: hello
}]
})
这篇关于处理单页应用程序URL和Django URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!