使用 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM