我在服务器中有一个正在运行的node.js脚本。 我想要的是它不能直接从浏览器访问,我也希望只有某些域/ IP可以调用它! 有可能吗?!
答案 0 :(得分:1)
不确定如何区分从浏览器访问某些内容而不是其他软件,但是限制对某些域/ IP的访问应该是可行的。限制访问localhost循环的以下(非生产)代码可以作为起点:
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
另请参阅Express.js: how to get remote client address和How do I get the domain originating the request in express.js?
的更详细的SO答案