yangzhou33

概述

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

express路由和前端路由

之前用express搭建了一个https服务器,现在用这个服务器发现了一个坑,就是路由是由后端实现的,所以如果在浏览器直接输入登录页的网址的时候,会显示cannot get /login,所以这里需要把路由交给前端路由,方法是把所有的页面请求都代理到后端主目录/index.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的区别:

res.send: 主要是发送字符串
res.sendFile: 发送文件,如果文件的Content-Type是application/json,则浏览器会以json的格式解析;如果文件的Content-Type是text/html,则浏览器会以html的格式解析
res.render: 运用模板引擎来渲染输出,需要先定义模板引擎

值得说明的是,使用res.sendFile是满足需求的:

app.get(\'*\', function(req, res, next) {
  res.sendFile(path.join(__dirname, \'..\', \'dist/index.html\'));
});

但是这样会给所有的http请求都发送index.html这个页面,就不能获取同域名下的css和js了。所以最开始的需求有问题,我们不是对所有http请求都发送index.html!!!

最后只能通过connect-history-api-fallback这个插件解决,先安装这个插件,然后在server.js里面加上下面这段话即可:

app.use(require(\'connect-history-api-fallback\')());

webpack的devServer加上https

其实可以直接给webpack的devServer加上https,先用我上一篇博文类似的方法生成秘钥和公钥,然后在vue.config.js里面的devServer里面加入下面代码即可:

  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\'),
    },
  },

分类:

技术点:

相关文章:

  • 2021-11-13
  • 2021-11-13
  • 2021-12-10
  • 2021-04-13
  • 2021-12-15
猜你喜欢
  • 2022-12-23
  • 2021-09-02
  • 2021-12-25
  • 2022-02-08
  • 2022-12-23
  • 2021-05-29
  • 2021-08-30
相关资源
相似解决方案