如何在express服务器中从远程服务器获取JSON?

4
我希望您能够在服务器端复制jQuery的getJSON方法。 我使用的是Node.js服务器,使用Coffeescript编写的Express框架。
我客户端的代码如下:
# To get the client IP
$.getJSON("http://jsonip.com?callback=?", (data) ->
      # To get more information about that IP
  $.getJSON("http://freegeoip.net/json/" + data.ip, (fulldata) ->
    console.log fulldata))

fulldata变量给我关于客户端IP的信息。

由于需要避免在客户端使用JavaScript,因此我尝试在服务器端完成同样的操作,我使用以下方法获取客户端IP:

(req, res) ->
  # To get the client IP
  req.ip

但之后,我不知道如何从freegeoip.net服务器获取完整的JSON数据。
有人能帮忙吗?

http://nodejs.org/docs/v0.5.2/api/http.html#http.request - David Fregoli
https://github.com/mikeal/request - Carol Skelly
2个回答

1
我使用了Skelly的解决方案。
所以我做了:
request = require 'request'

(...)

(req, res) ->
  url = 'http://freegeoip.net/json/' + req.ip
  request.get(url, (error, response, body) ->
    if !error 
      console.log body
  )

身体包含我所需的数据。
我相信David Fregoli的原生node.js解决方案也可以工作,但Request包完美且易于使用。
感谢他们两个。

如果你只需要进行GET请求,node.js有一个类似于request模块的快捷方式。http://nodejs.org/docs/v0.5.2/api/http.html#http.get - Pickels

0

我不太熟悉Coffeescript,然而,Node.js的默认库之一叫做http(通常用于设置服务器),可以进行 HTTP 请求

var request = http.request({host: 'jsonip.com', port: 80, path: '?callback=?' , method: 'GET'}, function(res){
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接