我有一个网站,该网站旨在在同一节点项目中使用api调用。我希望大多数此类api调用仅可用于localhost网站。

是否没有不宣誓就只听本地主机的选项?

最佳答案

您可以将localhost与您编写的端口放在一起

app.listen(PORT_NUMBER,'localhost',function(){
   console.log('server started on '+PORT_NUMBER);
})


这将使您的整个节点服务器开始在localhost:PORT_NUMBER上进行侦听,但是如果您要在localhost上侦听某些路由,则可以将中间件放在对这些调用的调用上,并在中间件中编写代码以过滤掉所有不是从本地发出的调用。例如 :-

    app.get('/first',function(req,res){
    })

    // middleware to filter calls
    app.use(function(req,res,next){
      var ipOfSource = request.connection.remoteAddress;
      if(ipOfSource == '127.0.0.1' || ipOfSource == 'localhost') next();
    })

   // all routes which need to be need to accessed from localhost goes here.
    app.get('/will be accessible from localhost',function(req,res){

    })

09-25 17:18
查看更多