如何从node-express发送AJAX请求?

时间:2014-10-06 02:18:27

标签: ajax node.js

在节点快速服务器中,我收到了大量的IP地址,我想在客户端的地图上将其可视化。

由于数据集很大,我认为最好给客户端返回一个包含经度和纬度数组的json。

问题是,从IP地址到地理位置,我需要向api发送ajax请求。我可以在服务器上执行此操作吗?

   $.ajax({
        type: "GET",
        url: 'http://api/'+ip,
        dataType: "jsonp",
        success: function (res) {
         //do something;
        }
   });

感谢。

1 个答案:

答案 0 :(得分:1)

在服务器端,你会有类似的东西:

app.get('/api/:ip',function(req, res){
    var ip = req.params.ip;
    geolocalizeIp(ip,function(latlng){ //you have to write this function
      res.json(latlng);
    });
});

客户端可以使用:

   $.ajax({
        type: "GET",
        url: 'http://yourserver/api/'+ip,
        dataType: "json",
        success: function (res) {
         //res is yourArray, do stuff with it here;
        }
   });