Go to comments

vue打包后刷新页面路径错误

vue/cli 搭建的的工程打包后,测试打包 dist 目录,

刷新页面出现 Cannot GET /article 或者 Not Found,

开始以为是js代码的问题,实际是服务器没有对应的 /article 目录,百度后解决如下


Apache 服务器亲测可用,配置完 .htaccess 文件后要重新启动 Apache 服务


--------------------------------[ 分割线 ]--------------------------------


报错问题:

"vue打包后,刷新页面,路径错误"

通常指的是单页应用(SPA)使用了 Vue Router,并且使用了 HTML5 的 history 模式,

当用户直接访问非首页链接或者刷新页面时,可能会遇到404错误,因为服务器没有配置相应的后备路由来返回入口的HTML文件。


解决方法:

1、使用 Vue CLI 创建的项目,可以在 vue.config.js 文件中配置 publicPath 和 outputDir。

// vue.config.js
module.exports = {
  publicPath: '/your-app-path/', // 设置为你的应用部署的路径
  outputDir: 'dist', // 构建时输出目录
};


2、对于后端服务器,需要配置一个后备路由,使得对所有页面资源的请求都返回index.html文件。以下是一些常见服务器的配置示例:


Apache 在 .htaccess 文件中添加如下配置

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /your-app-path/
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /your-app-path/index.html [L]
</IfModule>


Nginx 在 Nginx 配置文件中添加如下配置

location /your-app-path/ {
  try_files $uri $uri/ /your-app-path/index.html;
}


Node.js (如Express)

// server.js 或 app.js
app.use('/your-app-path', express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});


确保替换 /your-app-path/ 为你的应用实际部署的路径,

以上配置能确保所有的路由请求都回退到 index.html,从而允许 Vue Router 在前端处理路由。


百度ai的回答

https://www.baidu.com/s?ie=UTF-8&wd=vue%E6%89%93%E5%8C%85%E5%90%8E+%E5%88%B7%E6%96%B0%E5%90%8E+%E8%B7%AF%E5%BE%84%E9%94%99%E8%AF%AF&tn=68018901_3_dg



Leave a comment 0 Comments.

Leave a Reply

换一张