Django集成Vue前端遇MIME类型不匹配导致资源阻塞问题
项目背景与目录结构
我正在构建一个Django后端、Vue.js前端的Web应用,目录结构如下:
reco_system_app/urls.py reco_system_app/settings.py recommender/urls.py recommender/views.py vueapp/ static/ templates/
关键配置文件代码
reco_system_app/urls.py
from django.contrib import admin from recommender.views import home from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('recommender.urls')), path('', home, name='home'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
reco_system_app/settings.py
STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]
recommender/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('movies/', views.get_random_movies, name='get_random_movies'), path('recommend/', views.get_recommendations, name='get_recommendations'), ]
recommender/views.py
import random from django.shortcuts import render from django.views.generic import TemplateView from django.http import JsonResponse class IndexView(TemplateView): template_name = 'index.html' def home(request): return render(request, "index.html") def get_random_movies(request): # Simulate a list of movies sample_movies = ["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction", "The Lord of the Rings: The Return of the King"] # Return a random sample of 5 movies movies = random.sample(sample_movies, 3) return JsonResponse({"movies": movies}) def get_recommendations(request): # For simplicity, assume the movies are passed as a comma-separated string in the query parameter selected_movies = request.GET.get('movies', '') selected_movies_list = selected_movies.split(',') # Simulate recommendations by shuffling the input movies random.shuffle(selected_movies_list) recommendations = selected_movies_list # In a real scenario, you'd query VertexAI here return JsonResponse({"recommendations": recommendations})
问题现象
- Vue前端单独运行
npm run serve正常 - Django服务器运行
python manage.py runserver 0.0.0.0:8000后API接口可正常调用,但无法加载前端页面,浏览器报错:
The resource from “http://0.0.0.0:8000/js/app.d193da3f.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
The resource from “http://0.0.0.0:8000/js/chunk-vendors.5c940eb9.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
已确认npm run build生成文件位置正确,在Docker容器中运行(命令:docker run -it --entrypoint /bin/sh -v ${PWD}:/workspace -p 8080:8080 -p 8000:8000 recommendation),且DEBUG = True已设置,请问问题出在哪里?
解决方案
1. Vue打包路径与Django静态资源路径不匹配
浏览器请求的/js/xxx.js不在Django静态资源处理范围内。Vue打包后的js、css默认放在dist/js、dist/css,需要修改Vue打包配置,让输出文件直接进入Django的static目录,并设置正确的公共路径:
在vueapp/vue.config.js中添加:
module.exports = { outputDir: '../static', // 打包输出到Django的static目录 publicPath: '/static/' // 静态资源的公共访问前缀 }
2. 模板中静态资源引用路径错误
index.html中直接引用/js/xxx.js会导致请求被Django根路由拦截,返回index.html(text/html类型),引发MIME不匹配错误。需要用Django的静态资源标签修改引用:
修改templates/index.html中的资源引用:
{% load static %} <script src="{% static 'js/app.d193da3f.js' %}"></script> <script src="{% static 'js/chunk-vendors.5c940eb9.js' %}"></script>
3. 路由拦截问题
Django根路由path('', home, name='home')会匹配所有未被其他路由捕获的请求,包括静态资源请求。确保static()路由规则在所有业务路由之后,避免静态资源请求被误拦截:
调整reco_system_app/urls.py:
urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('recommender.urls')), path('', home, name='home'), ] # 确保静态资源路由追加在最后 urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
4. 静态资源目录验证
确认Vue打包后的js、css文件确实存在于Django的BASE_DIR/static目录下,若路径不一致,需调整STATICFILES_DIRS配置指向正确的静态资源目录。
内容的提问来源于stack exchange,提问作者Ananda

