前言:
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