137人参与 • 2025-04-24 • Javascript
将 vue 项目部署到线上后出现 404 错误,通常是由于 路由配置、服务器设置或资源路径问题 导致的。
以下是常见原因及解决方案:
vue 默认使用 hash 模式(url 带 #),但若使用 history 模式(无 # 的 url),刷新页面时服务器会尝试匹配该路径,但实际不存在对应的文件,导致 404。
示例:
访问 https://example.com/user/123,服务器会查找 /user/123/index.html,但 vue 是单页应用(spa),所有路由应由前端处理。
方案 1:配置服务器重定向到 index.html
确保所有请求都返回 index.html,由 vue router 接管路由。
location / {
try_files $uri $uri/ /index.html;
}.htaccess):rewriteengine on
rewritebase /
rewriterule ^index\.html$ - [l]
rewritecond %{request_filename} !-f
rewritecond %{request_filename} !-d
rewriterule . /index.html [l]在部署设置中指定 rewrites 规则,指向 index.html。
方案 2:改用 hash 模式
在 vue router 中强制使用 hash 模式:
const router = new vuerouter({
mode: 'hash', // 默认是 'history'
routes: [...]
});打包后的资源路径错误,浏览器无法加载 js/css 文件。
常见于项目部署在子目录(如 https://example.com/subdir/),但静态资源引用的是绝对路径。
修改 vue.config.js,设置正确的 publicpath:
module.exports = {
publicpath: process.env.node_env === 'production' ? '/your-subdir/' : '/'
};publicpath: '/';/subdir/),用 publicpath: '/subdir/'。检查打包后的 index.html
确保引用的 js/css 路径正确,例如:
<script src="/subdir/js/app.123456.js"></script>
服务器未正确返回 .js、.css 等文件的 mime 类型,导致浏览器拒绝加载。
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header cache-control "public";
try_files $uri =404;
}.htaccess 包含:addtype application/javascript js addtype text/css css
dist 文件夹内容未完整上传到服务器。dist 文件夹。dist 内的所有文件(而非 dist 文件夹本身)。server {
root /path/to/your/dist;
index index.html;
}ctrl + f5 或 cmd + shift + r)。// vue.config.js
module.exports = {
filenamehashing: true // 默认开启
};index.html)。publicpath 是否正确)。error.log)。如果问题仍未解决,可以提供具体的 部署环境(nginx/apache/netlify 等) 和 错误日志,进一步分析!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论