【问题标题】:Restrict access to Node.js using Express使用 Express 限制对 Node.js 的访问
【发布时间】:2016-05-16 01:51:45
【问题描述】:

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

【问题讨论】:

  • 据我所知,Express 无法像 Nginx 和 Apache 那样自行执行条件块。所以我现在没有想法。

标签: javascript node.js express server restriction


【解决方案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 答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2020-11-12
    相关资源
    最近更新 更多