首页 > 解决方案 > 使用 React 的 HashRouter 时如何从 URL 中删除 static/index.html?

问题描述

我正在使用带有 DRF 后端的 React 前端,并且我将两者都托管在同一个 URL 上。我得到了前端的静态生产构建,并将它放在静态文件夹下,当一个人转到主 URLcontoso.com时,他们被重定向到contoso.com/static/index.html提供静态构建的位置,并且可以使用 HashRouter 正确访问不同的 URL 和重新加载页面等按预期工作,但链接如contoso.com/static/index.html#home,contoso.com/static/index.html#menu等。我只想在主 URL 下有contoso.com/#home, contoso.com/#menu。用于此的 API 后端存在于contoso.com/api.
附加信息:使用 wfastcgi 托管在 IIS v10 上,静态文件夹为公共

标签: reactjsiisdjango-rest-frameworkreact-router

解决方案


拳头像这样从 settings.py 更改模板代码

'DIRS': [
            os.path.join(BASE_DIR, '/static') #If index.html file is in static folder.
        ],

然后在project.urls.py

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
   #...
    path('', TemplateView.as_view(template_name='index.html')),
]

现在拔下您在评论中共享的先前视图,并使用此 URL 从 React 前端的构建中呈现 index.html。

然后这将按您的意愿工作。example.com/#home


推荐阅读