1、先了解vue路由几种模式
主要2种:
1、hash模式
2、history模式
看官方介绍:vue-Router
2、 接着上一篇文章看 微前端demo
vue + signle-spa 实现微前端demo:微前端demo
我们主项目app1使用了history路由模式
子项目app2使用了默认的hash模式的路由。
- 我们来看2中场景的404
1、是本地npm run serve开发阶段刷新非主页面路由404问题
2、上线后用nginx部署项目时刷新非主页面路由404问题
- 解决:本地npm run serve开发阶段刷新非主页面路由404问题
app1根目录下的 vue.config.js 配置修改
在devServer下增加 historyApiFallback 属性设置为true,
意思是:路由没有命中,就会自动render index.html
historyApiFallback 也有 其他写高级的写法,自行百度吧
const package = require('./package.json')
module.exports = {
// 告诉子应用在这个地址加载静态资源,否则会去基座应用的域名下加载
publicPath: './',
// 开发服务器
devServer: {
port: 8081,
historyApiFallback: true
},
configureWebpack: {
// 导出umd格式的包,在全局对象上挂载属性package.name,基座应用需要通过这个全局对象获取一些信息,比如子应用导出的生命周期函数
output: {
// library的值在所有子应用中需要唯一
library: package.name,
libraryTarget: 'umd'
}
}
}
-
修改好后直接把app1 、app2 启动起来访问子应用页面等非主页面路由就没有404问题了
-
解决:上线后用nginx部署项目时刷新非主页面路由404问题
6.1 把 app1 、app2 npm run build 生成dist目录
6.2 修改主应用的 nginx配置
主要是增加 try_files 配置
看nginx官方介绍:try_files
主要就是如果没有找到任何文件,uri则进行到最后一个参数中指定的内部重定向,就是重定向到index.html文件
server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#proxy_pass http://127.0.0.1:8081/;
root D:/shaoqi_workspace/single-spa-test/micro-frontend/app1/dist;
index index.html;
#root html;
#index index.html index.htm;
try_files $uri $uri/ @router;
}
location @router {
rewrite ^.*$ /index.html last;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ .php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ .php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param script_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /.ht {
# deny all;
#}
}
---------结束---------



