我确实在服务器中有一个正在运行的node.js脚本。
我想要的是它不能直接从浏览器访问,而且我还希望只有某些域/IP可以调用它!
是否可以?!
最佳答案
不确定如何区分从浏览器访问某些内容而不是其他软件,但是应该限制对某些域/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答案