我有一个工作的node.js restify服务器,配置为静态网络服务器。这是相关的代码;
var server = restify.createServer({
name: 'myapp',
version: '1.0.0'
});
var static_webserver = function (app) {
app.get(/.*/, restify.serveStatic({
'directory': 'static', //static html files stored in ../static folder
'default': 'index.html'
}));
} //var static_server = function (app)
static_webserver(server);
启用HTTP基本身份验证以使其他REST API具有更好的安全性后,静态Web服务器停止工作。
这是启用HTTP基本身份验证的代码。
server.use(restify.authorizationParser());
function verifyAuthorizedUser(req, res, next)
{
var users;
users = {
foo: {
id: 1,
password: 'bar'
}
};
if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
// Respond with { code: 'NotAuthorized', message: '' }
next(new restify.NotAuthorizedError());
} else {
next();
}
next();
}//function verifyAuthorizedUser(req, res, next)
server.use(verifyAuthorizedUser);
在启用身份验证后,似乎没有Web浏览器能够访问静态html网页,因为需要身份验证。如何禁用静态Web服务器的身份验证,但是为其他REST API启用身份验证?
答案 0 :(得分:1)
如果您的nodejs是最新的,足以支持string.startsWith()
:
function verifyAuthorizedUser(req, res, next) {
var path = req.path();
// check if the path starts with /static/
if (path.startsWith('/static/')) {
return next();
}
var users;
users = {
foo: {
id: 1,
password: 'bar'
}
};
if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
// Respond with { code: 'NotAuthorized', message: '' }
next(new restify.NotAuthorizedError());
} else {
next();
}
next();
}
如果你没有startsWith(),一个好的旧正则表达式会做:
if (path.match(/\/static\/.*/)) {
return next();
}