zoukankan      html  css  js  c++  java
  • nodejs 解决 vue,react history 模式,刷新404问题

    首先我们要明白一点,history 模式为什么刷新会404

    1、vue,react :history模式是采用浏览器的历史记录,浏览器窗口有一个history对象,用来保存浏览历史

    2、history渲染页面:当我们使用后端渲染页面: /build/index.html 时

      (1)例如:nodejs 渲染 index.html, 直接使用开放静态资源 app.use('/',express.static(path.join(__dirname, 'build')))  ,这样默认 “/” 路径即可访问 index.html 页面

      (2)但是当我们路由跳转时,从路由“/” 跳转到 “list”时,这时刷新页面 “/list” 就不会渲染 index.html 页面了,因为路径改变了,就不会渲染index.html 了

    3、hash渲染页面:当我们使用后端渲染页面: /build/index.html 时,因为使用的hash 模式路径并不会改变,会由路由 “/#/” 跳转到 “/#/list”,注意这里只是改变的hash值,后端并不读取hash值,所以还是根据路由 “/” 进行渲染 index.html

    解决 vue,react history 模式

    1、(Express 框架 官方推荐)使用第三方库   connect-history-api-fallback

    (1)安装  connect-history-api-fallback

    npm install connect-history-api-fallback --save

    (2)在app.js文件中使用

    const history = require('connect-history-api-fallback')
    app.use('/', history());

    (3)history() 传入参数覆盖默认的索引文件(我们知道 express.static 静态资源默认索引文件为index.html )

    history({
      index: '/default.html'
    });

    (4)history() 传入参数,根据url匹配 regex 模式时,重写索引。可以重写为静态字符串,也可以使用函数转换传入请求

    history({
      rewrites: [
        { from: //soccer/, to: '/soccer.html'}
      ]
    });

    2、使用 app.all('*') 监听所以请求   注意:一定写到所有后端接口路由最后面 !!!前台页面路由,不能和后端接口路由重复,不然会响应接口数据

    // 处理vue项目路由 history 模式问题 !!! 注意:一定写到所有后端接口路由最后面(前台页面路由,不能和后端接口路由重复 )
    app.all('*',(req, res, next)=>{
      res.set({
        'Content-Type': 'text/html; charset=utf-8'
      })
      res.sendFile(path.join(__dirname, '/build/index.html'));
    })
  • 相关阅读:
    HDU 1548 A strange lift (Dijkstra)
    HDU 1217 Arbitrage (Floyd)
    HDU 1385 Minimum Transport Cost (Dijstra 最短路)
    考研总结 2016-12-31 20:10 219人阅读 评论(21) 收藏
    归并排序 2016-12-30 20:17 208人阅读 评论(21) 收藏
    docker安装 2016-11-06 19:14 299人阅读 评论(31) 收藏
    Docker初步了解 2016-10-30 20:46 279人阅读 评论(31) 收藏
    [自考]感想 2016-10-23 20:28 261人阅读 评论(32) 收藏
    [自考]C++中一些特殊用法 2016-10-16 22:12 318人阅读 评论(30) 收藏
    Fitnesse批量读取变量信息,并保存到用例执行上下文中
  • 原文地址:https://www.cnblogs.com/liangziaha/p/15364225.html
Copyright © 2011-2022 走看看