zoukankan      html  css  js  c++  java
  • 使用 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
  • 相关阅读:
    FIREDAC(DELPHI10 or 10.1)提交数据给ORACLE数据库的一个不是BUG的BUG
    分布式系统的软肋——数据一致性
    原子操作
    Android---观察者模式的简单实现demo
    Android -- 获取网络数据并将数据存到本地数据库中
    加密模式
    Vue.js——vue-resource全攻略
    VUE---Missing space before function parentheses
    css:子元素div 上下左右居中方法总结
    扒取网站的源代码
  • 原文地址:https://www.cnblogs.com/alone2015/p/9013141.html
Copyright © 2011-2022 走看看