Implement a simple SPA static resource server using Express

background

Restricting SPA applications has become mainstream. In the project development stage, product managers and back-end development students often need to view the front-end pages. The following is the SPA static resource server solution commonly used by our team using express.

Add the sendFile of the entry (index.html) for the SPA application

When the SPA application enables html5 mode, all requests under the specified url ( <base href="/">in the case of /) will access the entry file (usually index.html), and then the SPA application will determine the actual page to visit according to the url.
So we need to add sendFile to all paths to send the content in the index.html file, and set its cache to 0. The code is as follows:

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

 

Add additional static resources for the SPA application

Due to the characteristics of Express middleware, we need to process other static resources before sendFile of index.html. The specific code is as follows:

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

 

All code for SPA static resource server

The following is the entire code of the SPA static resource server 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}`);

 

Execute the following command to specify the SPA project path and port number to start the server

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326001052&siteId=291194637