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 后端接口,从而避免页面报错。

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

相关推荐
二十雨辰9 分钟前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码19 分钟前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
JY-HPS27 分钟前
echarts天气折线图
javascript·vue.js·echarts
黑色的糖果1 小时前
vue中tailwindcss插件的引入及使用
前端·javascript·vue.js
前端摸鱼匠1 小时前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测
WangYaolove13141 小时前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
AALoveTouch1 小时前
大麦网协议分析
javascript·python
ZH15455891312 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh2 小时前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh2 小时前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics