搭建微服务器(续)

概述

最近在研究服务器渲染,服务端渲染目前只支持node服务器,不支持其它语言的服务器,因此又入了express的坑,把心得记录下来,供之后开发时参考,相信对其余人也有用。css

express路由和前端路由

以前用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

其实能够直接给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'),
    },
  },
相关文章
相关标签/搜索