使用koa处理vue项目的history模式
在vue项目的路由中默认是hash模式,又叫前端路由,根据浏览器url地址栏中的变化,使用onhashchange
事件监听做出相应的操作,不会向服务器发送请求。但是若采用了history模式,就大大不同了,history不怕前进不怕后退就怕刷新,history模式是由浏览器提供的history api
来处理。而且将vue项目(非ssr)打包后的静态资源部署到不同的服务器中,服务器的配置也不同。这里我首先使用了nodejs提供的koa网络服务框架来解决这一问题。
vue打包
我这里使用的是vue-cli 4.x版本,这里要注意,若你使用的vue-cli在3.0及其以上,在vue.config.js
配置文件中basePath配置项要使用publicPath来代替。在生产环境下要将publicPath设置为/
根路径,为了我们的资源重定向。然后将路由模式设置为history
模式。
// router.js
const router = new VueRouter({
mode: 'history',
routes
})
koa服务
这里面的主角是koa2-connect-history-api-fallback
这个中间件。这个中间件是基于connect-history-api-fallback
实现,新增了白名单,不是让所有404都指向index.html。
传送门:
koa2-connect-history-api-fallback
connect-history-api-fallback
依赖:
yarn add koa koa-router koa-static koa2-connect-history-api-fallback
启动文件:
const path = require('path');
const Koa = require('koa');
const Router = require('koa-router');
const static = require('koa-static');
const { historyApiFallback } = require('koa2-connect-history-api-fallback');
const app = new Koa();
const router = new Router();
app
// koa2-connect-history-api-fallback中间件一定要放在静态资源服务中间件前面加载
.use(historyApiFallback({
index: '/index.html'
}))
// 配置静态资源服务中间件,指定域名根目录的映射
.use(static(path.join( __dirname, '/public')))
// 配置路由
router
.get('/', async ctx => {
ctx.render('index');
})
// 其他路由匹配规则....
// 应用路由
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
部署
将打包后的vue项目放在服务端的静态资源public
(案例中的位置)文件夹中,启动服务文件就可以了。
服务端目录结构:
|——node_modules/
|——public/
|———assets/
|———favicon.ico
|———index.html
|——server.js
|——yarn.lock
|——package.json
Nginx部署Vue项目,history模式配置
Nginx静态部署主要解决两个痛点
- 刷新404,我们可以用重定向解决
- 资源请求跨域处理,可以配置请求头。
server
{
listen 80;
listen 443 ssl http2;
server_name [你的域名];
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/[你站点文件夹];
# 图标404请求根路径
location ~ ^/favicon\.ico$ {
root /www/wwwroot/[你站点文件夹];
}
# 防止请求跨域
location / {
index index.html index.htm;
try_files $uri $uri/ @fallback;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# history刷新404重定向到index.html
location @fallback {
rewrite ^.*$ /index.html break;
}
....
}
文章推荐
其他服务端还未测试,推荐一篇文章,有兴趣的小伙伴可以测试一下。
vue路由的两种模式配置以及history模式下面后端如何配置