使api调用只听localhost

时间:2015-07-14 04:29:28

标签: javascript node.js security express mean-stack

我有一个网站,它被构建为在同一个节点项目中使用api调用。我希望这些api调用中的大部分只能在localhost网站上使用。

是不是没有使用誓言的选项而只是听localhost?

1 个答案:

答案 0 :(得分:1)

你可以把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){

    }) 

这将使您的整个节点服务器开始侦听localhost:PORT_NUMBER但是如果您想要在localhost上侦听某些路由,那么您可以将中间件置于这些调用上并在中间件中编写代码以过滤掉所有不是由当地制造。例如: -

<tr class='item'>
 <td class='itemId'>@item.ID</td>
 <input type="hidden" value="@item.ID" class='hiddenid'/>
 //other  html
</tr>