我们的Web应用程序正在使用需要基本身份验证的REST API。
我想写这样的browser-sync gulp任务:
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: './'
},
authenticate: 'authentication-token-here-djfhjsdfjsgdf'
});
});
怎么配置这个?
您可以使用处理每个请求的middleware
选项轻松完成:
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: './'
},
middleware: [
function(req, res, next) {
const user = 'user';
const pass = 'pass';
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();
}
}
]
});
});