5

vue项目打包,解决静态资源无法加载和路由加载无效(404)问题 - NGIWS

 11 months ago
source link: https://www.cnblogs.com/yj179101536/p/17758078.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

vue项目打包,解决静态资源无法加载和路由加载无效(404)问题

打包后的项目静态资源无法使用,导致页面空白

静态资源无法使用,那就说明项目打包后,图片和其他静态资源文件相对路径不对,此时找到config里面的index.js,在build模块下加入assetsPublicPath: './', 如下图所示,

       

2576900-20231011194222242-2015760857.png

在History模式下配合使用nginx运行打包后的项目

当刷新当前路由的时候,就会出现404的状况,其实这是因为当刷新当前页面时候,所需要访问的资源在服务器上找不到,也就是说,我们在Vue开发应用的过程中,设置路由的路径不是真实存在的路径,并且使用了history模式。

这是由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/id(假设此url在开发中是可以访问的),也会得到一个 404 错误。

解决方法:在部署项目的服务器上找到nginx的配置文件nginx.conf添加以下内容

server { listen 80; #监听80端口 server_name audio; #设置server_name名为audio,切记不能与配置文件中的其他server_name重名 location / { try_files $uri $uri/ /index.html; #使用history模式进行路由 root C:\phpstudy_pro\WWW; #将打包好的dist文件夹中的内容放进WWW文件夹中 autoindex on; #开启nginx目录浏览功能 autoindex_exact_size off; #文件大小从KB开始显示 charset utf-8; #显示中文 add_header 'Access-Control-Allow-Origin' '*'; #允许来自所有的访问地址 add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS'; #支持请求方式 add_header 'Access-Control-Allow-Headers' 'Content-Type,*'; add_header 'Access-Control-Allow-Headers' 'x_hztz_token,*'; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }

注意:配置完nginx后使用命令进行重载

nginx -s reload

或手动重启nginx服务


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK