天天看点

history路由模式与hash路由模式的区别

history路由模式与hash路由模式两种单页应用的路由模式 区别

hash模式

hash模式 :使用 URL 的 hash 来模拟一个完整的 URL, 其显示的网络路径中会有 “#” 号

hash 虽然出现URL中,但不会被包含在HTTP请求中,对后端完全没有影响,因此改变hash后刷新, 也不会有问题

hash模式示例: http://localhost:8080/#/home http://localhost:8080/#/user

原理: hashChange

history模式

history模式: 美化后的hash模式,路径中不包含“#”。依赖于Html5 的

history api

由于改变了地址, 刷新时会按照修改后的地址请求后端, 需要后端配置处理, 将地址访问做映射, 否则会404

history模式示例: http://localhost:8080/home http://localhost:8080/user

原理: popState, pushState()

vue项目修改路由模式

修改路由模式从hash转变为history模式

开发到现在,我们一直都在用hash模式,打包我们尝试用history模式

改成history模式非常简单,只需要将路由的mode类型改成history即可。在

src/router/index.js

// 创建路由实例
const createRouter = () => new Router({
  mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  // 指定路由规则
  routes: [
    ...constantRoutes // 静态路由, 首页
  ]
})
           

配置好之后,我们访问路径不再需要加#号同样运行正常,这是因为 webpack 默认配好了对于 history 模式的处理

在nodejs环境中布署应用-解决history

问题

将history模式下打包的代码放置服务器运行,出错:浏览器一刷新就会出现页面丢失的问题

原因

首次运行

history路由模式与hash路由模式的区别

再次刷新

history路由模式与hash路由模式的区别

为什么hash模式刷新不报错

history路由模式与hash路由模式的区别

### 解决history页面访问问题

安装 koa中间件

注册中间件

const Koa  = require('koa')
const serve = require('koa-static');
const { historyApiFallback } = require('koa2-connect-history-api-fallback');
const app = new Koa();
// 这句话 的意思是除接口之外所有的请求都发送给了 index.html
app.use(historyApiFallback({ 
  whiteList: ['/api']
}));  // 这里的whiteList是 白名单的意思

app.use(serve(__dirname + "/public")); //将public下的代码静态化

app.listen(3333, () => {
  console.log('项目启动')
})
           

此时解决了刷新 404 的问题 (注意: 如果点了登录, 记得清除cookies 再测试)

继续阅读