Django部署vue项目报错:Not Found The requested resource was not found on this server.

这个问题通常是由于前端路由和后端路由的冲突导致的。在Vue项目中,通常使用Vue Router来处理前端路由,而在Django中,也有自己的路由系统。当你刷新页面时,浏览器会直接向服务器请求当前URL对应的资源,而不是通过Vue Router来处理。

为了解决这个问题,你可以通过以下几种方法来处理:

方法一:使用HTML5 History 模式

Vue Router 默认使用的是 hash 模式,这种模式下 URL 中会有一个 # 符号,例如 200.com/#/server。这种模式下刷新页面不会导致问题,因为 # 后面的内容不会被发送到服务器。但是,如果你希望 URL 更美观,可以使用 HTML5 History 模式。

  1. 在 Vue Router 中启用 HTML5 History 模式:

    javascript 复制代码
    const router = new VueRouter({
      mode: 'history',
      routes: [
        // your routes
      ]
    });
  2. 在 Django 中配置路由,使其能够处理所有前端路由请求并返回 index.html

    python 复制代码
    from django.urls import path
    from django.views.generic import TemplateView
    
    urlpatterns = [
        path('', TemplateView.as_view(template_name='index.html')),
        path('<path:path>', TemplateView.as_view(template_name='index.html')),
    ]

方法二:使用中间件处理前端路由

你也可以创建一个 Django 中间件来处理所有前端路由请求,并返回 index.html

  1. 创建一个中间件文件 frontend_middleware.py

    python 复制代码
    from django.http import HttpResponse
    from django.template import loader
    
    class FrontendMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            if request.path.startswith('/api'):
                return self.get_response(request)
    
            template = loader.get_template('index.html')
            return HttpResponse(template.render({}, request))
  2. 在 Django 设置中添加中间件:

    python 复制代码
    MIDDLEWARE = [
        # other middleware classes
        'your_app.frontend_middleware.FrontendMiddleware',
    ]

方法三:使用 Nginx 或其他 Web 服务器进行重写

如果你使用 Nginx 或其他 Web 服务器来部署你的 Django 应用,你可以在服务器配置中进行 URL 重写,将所有前端路由请求重写到 index.html

  1. 在 Nginx 配置文件中添加以下内容:

    nginx 复制代码
    location / {
        try_files $uri $uri/ /index.html;
    }

通过以上方法,你可以确保在刷新页面时,前端路由能够正确处理,而不是直接请求 Django 后端接口,从而避免页面报错。

在本次问题中,我们使用了方法一解决了问题!

相关推荐
西西弗Sisyphus35 分钟前
全面掌握Python时间处理
python·time
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-http响应状态码
python·flask·flask3
奔跑吧邓邓子4 小时前
【Python爬虫(12)】正则表达式:Python爬虫的进阶利刃
爬虫·python·正则表达式·进阶·高级
码界筑梦坊4 小时前
基于Flask的京东商品信息可视化分析系统的设计与实现
大数据·python·信息可视化·flask·毕业设计
pianmian14 小时前
python绘图之箱型图
python·信息可视化·数据分析
csbDD5 小时前
2025年网络安全(黑客技术)三个月自学手册
linux·网络·python·安全·web安全
赔罪6 小时前
Python 高级特性-切片
开发语言·python
伊一大数据&人工智能学习日志6 小时前
selenium爬取苏宁易购平台某产品的评论
爬虫·python·selenium·测试工具·网络爬虫
说是用户昵称已存在7 小时前
Pycharm+CodeGPT+Ollama+Deepseek
ide·python·ai·pycharm
程序员黄同学7 小时前
请谈谈 Vue 中的响应式原理,如何实现?
前端·javascript·vue.js