1 | 'use strict';
|
2 |
|
3 | const express = require('express');
|
4 | const serveStatic = require('serve-static');
|
5 | const compression = require('compression');
|
6 | const auth = require('basic-auth');
|
7 |
|
8 | const setCustomCacheControl = (res, path) => {
|
9 | if (process.env.NODE_ENV !== 'production') {
|
10 | res.setHeader('Cache-Control', 'public, max-age=0')
|
11 | } else {
|
12 | if (serveStatic.mime.lookup(path) === 'text/html') {
|
13 | res.setHeader('Cache-Control', 'public, max-age=0')
|
14 | }
|
15 | }
|
16 | }
|
17 |
|
18 | module.exports = function(app, options) {
|
19 |
|
20 | app.use(compression());
|
21 |
|
22 | app.use(function(req, res, next) {
|
23 | if (options.user && options.password) {
|
24 | var user = auth(req);
|
25 | if (user === undefined || user['name'] !== options.user || user['pass'] !== options.password) {
|
26 | res.statusCode = 401;
|
27 | res.setHeader('WWW-Authenticate', 'Basic realm="node-serve"');
|
28 | res.end('Unauthorized');
|
29 | } else {
|
30 | next();
|
31 | }
|
32 | } else {
|
33 | next();
|
34 | }
|
35 | });
|
36 |
|
37 | app.use(function(req, res, next) {
|
38 | res.setHeader('Access-Control-Allow-Origin', '*');
|
39 | res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE');
|
40 | res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
|
41 | res.setHeader('Access-Control-Allow-Credentials', true);
|
42 |
|
43 | if (process.env.NODE_ENV !== 'production') {
|
44 | res.setHeader('X-Robots-Tag', "noindex, nofollow");
|
45 | }
|
46 |
|
47 | next();
|
48 | });
|
49 |
|
50 | app.use(serveStatic(options.path, {
|
51 | 'index': ['index.html'],
|
52 | 'dotfiles': 'ignore',
|
53 | 'maxAge': '30d',
|
54 | 'setHeaders': setCustomCacheControl
|
55 | }));
|
56 |
|
57 | app.get('*', function(req, res) {
|
58 | res.status(404).end();
|
59 | });
|
60 |
|
61 | } |
\ | No newline at end of file |