Vue中的Cannot GET / xxx

场景

  • Vue2.6.12

  • 模式:单页面应用(SPA)模式

  • 路由模式:history 模式

【问题一】 刷新页面,出现 Cannot GET / xxx

【解决】 设置 historyApiFallback: true

webpack.config.js

devServer: {
  ...
  historyApiFallback: true
  ...
}

【问题二】在问题一解决的基础上增加代理(proxy)配置,刷新页面,再次出现 Cannot GET / xxx问题,并且控制台还有报错信息

  • 配置

webpack.config.js

devServer: {
  ...
  historyApiFallback: true,
  proxy: {
    '/': {
      target: 'http://localhost:3000',
    }
  },
  ...
}
  • 问题

【解决】 设置 bypass

webpack.config.js

devServer: {
  ...
  historyApiFallback: true,
  proxy: {
    '/': {
      target: 'http://localhost:3000',
      bypass: function (req, res, proxyOptions) {
        if (req.headers.accept.indexOf('html') !== -1) {
          return 'index.html'; // SPA,只有一个html页面,所有都返回index.html页面(个人理解)
        }
      },
    }
  },
  ...
}

HtmlWebpackPlugin插件的配置

  • 输出的文件:index.html,所以上面 bypass 返回的是 index.html
new HtmlWebpackPlugin({
  title: 'Scaffolds',
  template: './public/index.ejs', // 指定模板html文件
  filename: 'index.html', // 输出的html文件名称
  favicon: './public/favicon.ico',
  hash: true,
  cache: true,
}),
posted @ 2020-12-24 22:13  LucasLin  阅读(1805)  评论(0编辑  收藏  举报