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;
        }

 

訪問結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM