браузер-синхронизация отключает просмотр каталогов для некоторых подкаталогов - PullRequest
0 голосов
/ 12 июня 2019

Я новичок в использовании синхронизации браузера и gulp, но в зависимости от использования я пытаюсь сделать мой http-сервер доступным через веб-сервер. Кроме того, я хочу исключить некоторые каталоги, которые нужно скрывать или не просматривать, используя атрибут отрицания для файлов, но он не работает ... Моя главная цель - определить некоторые каталоги, чтобы они всегда выдавали 404, что бы ни запрашивалось у них ...

Может кто-нибудь, пожалуйста, проверьте; если возможно, вот моя реализация gulp:

var gulp        = require('gulp');
var browserSync = require('browser-sync').create();
var files = ['d2cvib/output/**/*.{xml}','!d2cvib/changed-list/**'];
// Static server
gulp.task('browser-sync', function() {
    browserSync.init({files,
        port: 8203,
        server: {
            baseDir: "/mule_local_exchange/d2c/",
            middleware: [
            function(req, res, next) {
                const user = 'd2c';
                const pass = 'd2cweb';
                let authorized = false;
                // See if authorization exist in the request and matches username/password
                if (req.headers.authorization) {
                    const credentials = new Buffer(req.headers.authorization.replace('Basic ', ''), 'base64').toString().split(/:(.*)/)
                      if (credentials[0] === user && credentials[1] === pass) {
                          authorized = true;
                      }
                }
                if (authorized) {
                    // Proceed to fulfill the request
                    next();
                } else {
                    // Authorization doesn't exist / doesn't match, send authorization request in the response header
                    res.writeHead(401, {'WWW-Authenticate': 'Basic realm="Authenticate"'})
                    res.end();
                }
            }

        ],
        directory: true
        }    
        });
});

1 Ответ

0 голосов
/ 12 июня 2019

Я не могу отключить список каталогов; но для решения проблемы я отключил код ответа, если HTTP GET запрашивал некоторые из каталогов, а не% 100 чистое решение, но работает для моего случая:

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var cache = require('gulp-cache');

//For conditions of rest-uri patterns
function buildSearch(substrings) {
  return new RegExp(
    substrings
    .map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
    .join('{1,}|') + '{1,}'
  );
}


gulp.task('clear-cache', function() {
  // Or, just call this for everything
  cache.clearAll();
});

// Static server
gulp.task('browser-sync', function () {
    browserSync.init({
        port: 8203,
        server: {
            baseDir: "/mule_local_exchange/d2c/",
            middleware: [
                function (req, res, next) {
                    const user = 'd2c';
                    const pass = 'd2cweb';
                    var pattern = buildSearch(['changed-list','current', 'changed_list']);
                    let authorized = false;
                    // See if authorization exist in the request and matches username/password
                    if (req.headers.authorization) {
                        const credentials = new Buffer(req.headers.authorization.replace('Basic ', ''), 'base64').toString().split(/:(.*)/)
                        if (credentials[0] === user && credentials[1] === pass) {
                            authorized = true;
                        }
                    }
                    if (authorized) {

                        if (pattern.test(req.url)) { //400 for not required directories
                            res.writeHead(400, {'Response':'Bad-request'})
                            res.end();
                        } else { // Proceed to fulfill the request
                            next();
                        }
                    } else {
                        // Authorization doesn't exist / doesn't match, send authorization request in the response header
                        res.writeHead(401, {
                            'WWW-Authenticate': 'Basic realm="Authenticate"'
                        })
                        //res.send(401,{ 'Authentication' : 'Failed' })
                        res.end();
                    }
                }
            ],
            directory: true
        }
    });
});

Эта часть выполняет работу:

if (pattern.test(req.url)) { //400 for not required directories
                            res.writeHead(400, {'Response':'Bad-request'})
                            res.end();
                        }
...