Abstract: vue-router default hash mode-use the URL hash to simulate a complete URL, so when the URL changes, the page will not reload.

This article is shared from the HUAWEI cloud community " learning Vue Router, HTML5 History mode, because the history mode refresh page will appear 404 ", author: DevFeng.

The default hash mode of vue-router-uses the hash of the URL to simulate a complete URL, so when the URL changes, the page will not reload.

If you don't want a very ugly hash, we can use the routing history mode , which makes full use of the history.pushState API to complete the URL jump without reloading the page.

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

When you use the history mode, the URL is just like a normal URL, such as http://yoursite.com/user/id, and it looks good!

However, to play well in this mode, background configuration support is also required. Because our application is a single-page client application, if the background is not properly configured, when the user directly accesses http://oursite.com/user/id in the browser, it will return 404, which is not good.

So, you have to add a candidate resource that covers all situations on the server side: if the URL does not match any static resources, you should return the same index.html page, which is the page your app depends on.

Backend configuration example

Note: following example assumes that you are serving this application in the root directory. If you want to deploy to a subdirectory, you need to use the publicPath option of Vue CLI (opens new window) and the related router base property (opens new window). You also need to adjust the root directory in the following example to a subfolder (for example, replace RewriteBase / with RewriteBase /name-of-your-subfolder/).

Apache

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

In addition to mod_rewrite, you can also use FallbackResource (opens new window).

nginx

location / {
  try_files $uri $uri/ /index.html;
}

Native Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.html', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

Express based on Node.js

For Node.js/Express, please consider using connect-history-api-fallback middleware (opens new window).

Internet Information Services (IIS)

  1. Install IIS UrlRewrite(opens new window)
  2. Create a web.config file in the root directory of your website with the following content:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
     <rewrite>
       <rules>
         <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
           <match url="(.*)" />
           <conditions logicalGrouping="MatchAll">
             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
             <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
           </conditions>
           <action type="Rewrite" url="/" />
         </rule>
       </rules>
     </rewrite>
      </system.webServer>
    </configuration>

    Caddy

    rewrite {
     regexp .*
     to {path} /
    }

    Firebase host

    Add in your firebase.json:

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

warn

A warning, because after doing this, your server will no longer return a 404 error page, because the index.html file will be returned for all paths. In order to avoid this situation, you should cover all routing conditions in the Vue application, and then give a 404 page.

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})

Or, if you use a Node.js server, you can use server-side routing to match the incoming URL, and return a 404 when the routing is not matched to achieve fallback.

Click to follow, and learn about Huawei Cloud's fresh technology for the first time~


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量