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

J M*_*Mon 5 javascript restriction node.js express server

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

tra*_*r53 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
Run Code Online (Sandbox Code Playgroud)

另请参阅 Express.js 的更详细 SO 答案:如何获取远程客户端地址如何获取在express.js 中发起请求的域?