vue-router
默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,於是當 URL 改變時,頁面不會重新加載。
如果不想要很丑的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState
API 來完成 URL 跳轉而無須重新加載頁面。
const router = new VueRouter({ mode: 'history', routes: [...] })
當你使用 history 模式時,URL 就像正常的 url,例如 http://yoursite.com/user/id
,也好看!
不過這種模式要玩好,還需要后台配置支持。因為我們的應用是個單頁客戶端應用,如果后台沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id
就會返回 404,這就不好看了。
所以呢,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html
頁面,這個頁面就是你 app 依賴的頁面。
以下為nodejs的后台配置:
本人當前項目結構為:
其中server為打包之后創建的新文件:
// server.js const http = require('http') const fs = require('fs') const httpPort = 8090 http.createServer((req, res) => { if (req.url.startsWith('/static/css') || req.url.startsWith('/static/js')) { fs.readFile('.' + req.url, (err, data) => { res.end(data); return; }) } fs.readFile('index.html', '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) })
在dist目錄下,開啟當前的node服務(node server.js),然后訪問 localhost:8090 即可訪問,然后在路由的任何頁面刷新,都不會出現404,這樣就完美解決了