使用Express限制对Node.js的访问

时间:2016-02-05 23:11:27

标签: javascript node.js express server restriction

我在服务器中有一个正在运行的node.js脚本。 我想要的是它不能直接从浏览器访问,我也希望只有某些域/ IP可以调用它! 有可能吗?!

1 个答案:

答案 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 &ndash; Not Found<\/span>');
}
var app = express();
app.use(securityCheck);  // restrict access
... // continue with app routing

另请参阅Express.js: how to get remote client addressHow do I get the domain originating the request in express.js?

的更详细的SO答案