使用 Express 实现一个简单的 SPA 静态资源服务器

背景

限制 SPA 应用已经成为主流,在项目开发阶段产品经理和后端开发同学经常要查看前端页面,下面就是我们团队常用的使用 express 搭建的 SPA 静态资源服务器方案。

为 SPA 应用添加入口(index.html)的 sendFile

当 SPA 应用开启 html5 mode 的情况下,指定 url 下(<base href="/">的情况为/)的全部请求都会访问入口文件(一般情况下是 index.html),然后 SPA 应用会根据 url 再去决定访问的实际页面。
所以我们需要为全部路径添加 sendFile 来发送 index.html 文件内的内容,并将其缓存实际设为0,代码如下:

1
2
3
app.use("/**", function (req, res) {
res.sendfile(staticPath+"/index.html", {maxAge: 0});
});

 

为 SPA 应用添加其他静态资源

由于 Express 中间件的特性,在 index.html 的 sendFile 之前我们需要将其他静态资源进行处理,具体代码如下:

1
2
3
const options = process.env.env == 'prod' ? {maxAge: '3d'} : {maxAge: '1m'};
app.use(express.static(path.join(__dirname, staticPath), options));
});

 

SPA 静态资源服务器的全部代码

下面是 SPA 静态资源服务器 app.js 的全部代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const express = require('express');
const path = require('path');
const http = require('http');

const app = express();
const staticPath=process.env.static ||'dist';
const port=process.env.port || 3000;

const options = process.env.env == 'prod' ? {maxAge: '3d'} : {maxAge: '1m'};
app.use(express.static(path.join(__dirname, staticPath), options));

app.use("/**", function (req, res) {
res.sendfile(staticPath+"/index.html", {maxAge: 0});
});

const server = http.createServer(app);
server.listen(port);

console.log(`env:${process.env.env}`);
console.log(`path:${staticPath}`);
console.log(`port:${port}`);

 

执行以下命令即可指定 SPA 项目路径和端口号启动服务器了

1
export static=www&&export port=8101 && export env=prod && node ./app.js

转载于:https://www.cnblogs.com/alone2015/p/9013141.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值