vue项目如何部署?有遇到布署服务器后刷新404问题吗?

275 阅读1分钟

参考文献:

github

总结:

vue项目在本地时运行正常,但部署到服务器中,刷新页面,出现了404错误

404 意味着链接指向的资源不存在

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的情况。

解决方案:

对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 }
  ]
})

关于后端配置方案还有:Apachenodejs等,思想是一致的,这里就不展开述说了