用於默認模式vue-router
爲散模式 -它使用URL的哈希來模擬一個完整的URL,這樣的頁面不會被重新加載的URL發生變化時。
爲了擺脫哈希,我們可以使用路由器的歷史模式,它利用history.pushState
API實現URL導航而無需重新加載頁面:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
使用歷史記錄模式時,URL將顯示爲“正常”,例如http://oursite.com/user/id
。
但是出現了一個問題:由於我們的應用程序是單頁客戶端應用程序,如果沒有正確的服務器配置,如果用戶http://oursite.com/user/id
直接在瀏覽器中訪問,則會收到404錯誤。現在那很難看。
不用擔心:要解決此問題,您需要做的就是向服務器添加一個簡單的全部回退路由。如果網址與任何靜態資源都不匹配,則該網址應與index.html
您的應用所在的網頁相同。
示例服務器配置
#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>
而不是mod_rewrite
,你也可以使用。FallbackResource
#nginx的
location / {
try_files $uri $uri/ /index.html;
}
#本地的Node.js
const http = require('http')
const fs = require('fs')
const httpPort = 80
http.createServer((req, res) => {
fs.readFile('index.htm', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.htm" 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)
})
#表達Node.js
對於Node.js / Express,請考慮使用connect-history-api-fallback中間件。
#Internet信息服務(IIS)
- 安裝IIS UrlRewrite
web.config
使用以下內容在站點的根目錄中創建文件:
<?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 hosting
將此添加到您的firebase.json
:
{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
注意
有一點需要注意:您的服務器將不再報告404錯誤,因爲所有未找到的路徑現在都會提供您的index.html
文件。要解決此問題,您應該在Vue應用程序中實現一個全能路徑以顯示404頁面:
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
或者,如果您使用的是Node.js服務器,則可以通過使用服務器端的路由器來匹配傳入的URL來實現回退,如果沒有匹配的路由,則使用404進行響應。有關更多信息,請查看Vue服務器端呈現文檔。
參考文檔:https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations