Vue 项目部署
1. 如何部署
前后端分离开发模式下,前后端是独立部署的,前端只需要将最后的构建物上传至目标服务器的 web 容器指定的静态目录下即可。
我们知道 vue 项目在构建后,是生成一系列的静态文件。常规部署只需要将这个目录上传至目标服务器即可:
# scp 上传 user 为主机登录用户,host 为主机外网 ip,xx 为 web 容器静态资源路径
scp dist.zip user@host:/xx/xx/xx
让 web 容器跑起来,以 nginx 为例:
server {
listen 80;
server_name www.xxx.com;
location / {
index /data/dist/index.html;
}
}
配置完成记得重启 nginx:
# 检查配置是否正确
nginx -t
# 平滑重启
nginx -s reload
2. 为什么部署项目会遇到 404
这是一个经典的问题。HTTP 404 错误意味着链接指向的资源不存在。
问题在于:为什么不存在?且为什么只有 history 模式下会出现这个问题?
为什么 history 模式下有问题
Vue 是属于单页应用(SPA)。所有用户交互是通过动态重写当前页面,不管应用有多少页面,构建物都只会产出一个 index.html。
现在我们回头看 nginx 配置:
server {
listen 80;
server_name www.xxx.com;
location / {
index /data/dist/index.html;
}
}
当在地址栏输入 www.xxx.com 时,会打开 dist 目录下的 index.html 文件。然后跳转到 www.xxx.com/login,此时执行刷新操作,nginx location 没有相关配置,所以就会出现 404。
为什么 hash 模式下没有问题
router hash 模式用符号 # 表示,如 website.com/#/login,hash 的值为 #/login。
它的特点在于:hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对服务端完全没有影响,因此改变 hash 不会重新加载页面。
hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如 website.com/#/login 只有 website.com 会被包含在请求中,因此对于服务端来说,即使没有配置 location,也不会返回 404 错误。
3. 解决方案
产生问题的本质是因为我们的路由是通过 JS 来执行视图切换的。当我们进入到子路由时刷新页面,web 容器没有相对应的页面此时会出现 404。所以我们只需要配置将任意页面都重定向到 index.html,把路由交由前端处理。
对 nginx 配置文件 .conf 修改,添加 try_files $uri $uri/ /index.html;:
server {
listen 80;
server_name www.xxx.com;
location / {
index /data/dist/index.html;
try_files $uri $uri/ /index.html;
}
}
修改完配置文件后记得平滑更新:
nginx -s reload
这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后再给出一个 404 页面:
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
来源整理自:vue3js.cn 面试官系列



