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

Restrict access to Node.js using Express

本文关键字:js 访问 Node Express 使用      更新时间:2023-09-26

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

不确定如何区分从浏览器访问某些内容而不是从其他软件访问某些内容,但限制对某些域/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

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