使用Express限制访问Node.js

6

我在服务器上运行着一个node.js脚本。 我希望它不会被直接从浏览器访问,并且只允许特定的域名/IP地址调用它! 这是可能的吗?


据我所知,Express 无法像 Nginx 和 Apache 那样自行执行条件块。因此,目前我已经没有更多的想法了。 - J Mon
1个回答

2

不确定如何区分从浏览器访问还是其他软件访问,但限制对某些域名/IP的访问应该是可行的。以下(非生产)代码限制对本地回环的访问可能作为起点:

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

还可以查看更详细的SO答案,以获取Express.js:如何获取远程客户端地址在express.js中如何获取请求的域源?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接