使用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
文章推荐
其他服务端还未测试,推荐一篇文章,有兴趣的小伙伴可以测试一下。
vue路由的两种模式配置以及history模式下面后端如何配置