最近在研究服務器渲染,服務端渲染目前只支持node服務器,不支持其它語言的服務器,因此又入了express的坑,把心得記錄下來,供之後開發時參考,相信對其餘人也有用。css
以前用express搭建了一個https服務器,如今用這個服務器發現了一個坑,就是路由是由後端實現的,因此若是在瀏覽器直接輸入登陸頁的網址的時候,會顯示cannot get /login,因此這裏須要把路由交給前端路由,方法是把全部的頁面請求都代理到後端主目錄/index.html。html
那麼開始嘗試:前端
app.use(express.static(path.join(__dirname, '..', 'dist'))); app.use('*', express.static(path.join(__dirname, '..', 'dist/index.html'))); app.get('*', express.static(path.join(__dirname, '..', 'dist/index.html'))); app.all('*', express.static(path.join(__dirname, '..', 'dist/index.html'))); app.get('*', function(req, res) { res.sendFile(path.join(__dirname, '..', 'dist/index.html')); }); app.set('views', path.join(__dirname, '..', 'dist/index.html')); app.set('view engine', 'html'); app.get('*', function(req, res, next) { res.render('index', { title: 'Express' }); }); app.get('*', function(req, res, next) { res.sendFile(path.join(__dirname, '..', 'dist/index.html')); }); app.get('*', function(req, res, next) { res.send(path.join(__dirname, '..', 'dist/index.html')); });
惋惜的是,上面的方法所有不行,下面來講所res.send, res.sendFile和res.render的區別:vue
res.send: 主要是發送字符串 res.sendFile: 發送文件,若是文件的Content-Type是application/json,則瀏覽器會以json的格式解析;若是文件的Content-Type是text/html,則瀏覽器會以html的格式解析 res.render: 運用模板引擎來渲染輸出,須要先定義模板引擎
值得說明的是,使用res.sendFile是知足需求的:node
app.get('*', function(req, res, next) { res.sendFile(path.join(__dirname, '..', 'dist/index.html')); });
可是這樣會給全部的http請求都發送index.html這個頁面,就不能獲取同域名下的css和js了。因此最開始的需求有問題,咱們不是對全部http請求都發送index.html!!!webpack
最後只能經過connect-history-api-fallback這個插件解決,先安裝這個插件,而後在server.js裏面加上下面這段話便可:web
app.use(require('connect-history-api-fallback')());
其實能夠直接給webpack的devServer加上https,先用我上一篇博文相似的方法生成祕鑰和公鑰,而後在vue.config.js裏面的devServer裏面加入下面代碼便可:express
devServer: { https: { key: fs.readFileSync(path.resolve(__dirname, './server/certificate/example.com+3-key.pem'), 'utf8'), cert: fs.readFileSync(path.resolve(__dirname, './server/certificate/example.com+3.pem'), 'utf8'), }, },