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,
}),


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM