HTML5 History 模式 去除# (vue路由去除#、常见配置、Tomcat配置)

前言:

vue使用vue-router时,路径中会有#的字段,是应为打包完成之后,项目为单页面项目,所有的url都指向单个页面,#号之后的路径是指该页面的锚定位置,所以router中的路径是无法加载的。

若想去除#,就需要使用router的history模式, 且在服务器端进行配置

核心:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

官网给出的解决方案:

1.Apache

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

除了 mod_rewrite,你也可以使用 FallbackResource

2.nginx

location / {
  try_files $uri $uri/ /index.html;
}

3.原生 Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80
 
http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }
 
    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })
 
    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

4.还有一个是Internet Information Services (IIS)

5.Tomcat

在打包后的文件中创建WEB-INF文件夹,
在WEB-INF文件中创建web.xml文件,内如如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <display-name>/</display-name>
  <description>/</description>
	<error-page>
		<error-code>404</error-code>
		<location>/index.html</location>
	</error-page>
</web-app>

扩展一下,是不是每次大包项目都要手动添加WEB-INF/web.xml呢。答案不是的,解决方案如下:

webpack(copy-webpack-plugin)插件配置信息中添加如下代码:

我的打包配置文件名为:webpack.prod.conf.js ,添加内容如下:

插件使用参考:https://blog.csdn.net/weixin_43369521/article/details/82987038

// copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      },
      {
        from: path.resolve(__dirname, '../WEB-INF'),
        to: 'WEB-INF',
        ignore: ['.*']
      }
    ])

在项目中添加与static文件夹同级别的WEB-INF文件,如下:
在这里插入图片描述
参考文献:

https://blog.csdn.net/elisunli/article/details/79823245

http://www.manongjc.com/article/28693.html

vue
原文链接:https://blog.csdn.net/weixin_38047955/article/details/89244953

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值