vue router 原生html,Vue router 使用 History 模式导致页面请求 404
vue-router?默認(rèn) hash 模式 —— 使用 URL 的 hash 來(lái)模擬一個(gè)完整的 URL,于是當(dāng) URL 改變時(shí),頁(yè)面不會(huì)重新加載。
如果不想要很丑的 hash,我們可以用路由的?history 模式,這種模式充分利用?history.pushState?API 來(lái)完成 URL 跳轉(zhuǎn)而無(wú)須重新加載頁(yè)面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
復(fù)制代碼
當(dāng)你使用 history 模式時(shí),URL 就像正常的 url,例如 yoursite.com/user/id,也好看…
不過(guò)這種模式要玩好,還需要后臺(tái)配置支持。因?yàn)槲覀兊膽?yīng)用是個(gè)單頁(yè)客戶端應(yīng)用,如果后臺(tái)沒(méi)有正確的配置,當(dāng)用戶在瀏覽器直接訪問(wèn) oursite.com/user/id 就會(huì)返回 404,這就不好看了。
所以呢,你要在服務(wù)端增加一個(gè)覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源,則應(yīng)該返回同一個(gè) index.html 頁(yè)面,這個(gè)頁(yè)面就是你 app 依賴的頁(yè)面。
后端配置例子
注意:下列示例假設(shè)你在根目錄服務(wù)這個(gè)應(yīng)用。如果想部署到一個(gè)子目錄,你需要使用?Vue CLI 的?publicPath?選項(xiàng)?和相關(guān)的?router?base?property。你還需要把下列示例中的根目錄調(diào)整成為子目錄 (例如用?RewriteBase /name-of-your-subfolder/?替換掉?RewriteBase /)。
Apache
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./index.html [L]
復(fù)制代碼
除了 mod_rewrite,你也可以使用 FallbackResource。
nginx
location / {
try_files $uri $uri/ /index.html;
}
復(fù)制代碼
原生 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)
})
復(fù)制代碼
#基于 Node.js 的 Express
#Internet Information Services (IIS)
在你的網(wǎng)站根目錄中創(chuàng)建一個(gè)?web.config?文件,內(nèi)容如下:
復(fù)制代碼
#Caddy
rewrite {
regexp .*
to {path} /
}
復(fù)制代碼
#Firebase 主機(jī)
在你的?firebase.json?中加入:
{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
復(fù)制代碼
警告
給個(gè)警告,因?yàn)檫@么做以后,你的服務(wù)器就不再返回 404 錯(cuò)誤頁(yè)面,因?yàn)閷?duì)于所有路徑都會(huì)返回?index.html?文件。為了避免這種情況,你應(yīng)該在 Vue 應(yīng)用里面覆蓋所有的路由情況,然后在給出一個(gè) 404 頁(yè)面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})
復(fù)制代碼
或者,如果你使用 Node.js 服務(wù)器,你可以用服務(wù)端路由匹配到來(lái)的 URL,并在沒(méi)有匹配到路由的時(shí)候返回 404,以實(shí)現(xiàn)回退。更多詳情請(qǐng)查閱?Vue 服務(wù)端渲染文檔。
總結(jié)
以上是生活随笔為你收集整理的vue router 原生html,Vue router 使用 History 模式导致页面请求 404的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c# html文件转换word,C#实现
- 下一篇: vue 实例化几种方式_Vue双向数据绑