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