VUE 改成history 模式 刷新404 的问题

vue 路由的URL有两种模式,一种是 hash,一种是history ,history 模式更好看一些。

在使用hisory模式时,由于地址并不是真实存在,那么在刷新的情况下,这个会报404错误。

改成history 模式,如果在直接在根目录下访问还是比较简单的。

修改 webpack 的配置文件

config/index.js

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true,

将assetsSubDirectory 修改为 / .

修改 nginx.conf  配置

location / {
             alias   E:\\temp\\vuemb\\dist\\;
           index  index.html index.htm;
             try_files $uri $uri/ /index.html;
        }

http://localhost:8000/params/123

在访问这个地址时,我们可以直接输入这个地址就可以访问到了。

 如果我们希望使用一个上下文路径的时候,比如 http://localhost:8000/demo 这样访问,需要做如下更改。

config/index.js 修改为如下代码

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/demo',

assetsPublicPath 这个修改为 /demo

路由配置做如下修改

export default new Router({
    mode: 'history',
    base:'/demo',
  routes: [

这里需要增加一个base 配置,修改完成后重新编译代码。

修改nginx.conf 配置如下:

location /demo {
             alias   E:\\temp\\vuemb\\dist\\;
           index  index.html index.htm;
             try_files $uri $uri/ /demo/index.html;
        }

访问结果如下:

猜你喜欢

转载自www.cnblogs.com/yg_zhang/p/12222375.html