I do have a running node.js script located in a server. What i want is that it doesn't get directly accessed from browser and also i want that only certain domains/IP-s can call it! Is it possible?!
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Not sure how to distinguishing between accessing something from a browser as opposed to other software, but restricting access to some domains/IPs should be doable. The following (non production) code to restrict access to the localhost loop back might serve as a starting point:
function securityCheck( req, response, next)
{ var callerIP = req.connection.remoteAddress;
(callerIP == "::ffff:127.0.0.1" || callerIP == "::1") ? next() : reply404( response);
}
function reply404( response)
{ response.writeHead(404, {"Content-Type": "text/html"});
response.statusMessage = "Not Found";
console.log("reply404: statusCode: " + response.StatusCode);
response.end('<span style="font-weight: bold; font-size:200%;">ERROR 404 – Not Found<\/span>');
}
var app = express();
app.use(securityCheck); // restrict access
... // continue with app routing
See also more detailed SO answers to Express.js: how to get remote client address and How do I get the domain originating the request in express.js?