How to get JSON from a remote server on an express server?

I am looking for a way to replicate the jQuery getJSON method, but on the server side. The server I use is a node.js server with a pronounced framework written in coffeescript.

I have a client side:

# 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)) 

The fulldata variable gives me information about the client's IP address.

I need to avoid using the client side of JavaScript, so I try to make the same server side, I get the client IP:

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

But after that, I have no idea how to get fulldata in json from the freegeoip.net server.

Help someone?

+4
source share
2 answers

I used the Skelly solution.

So I did:

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

The body contains the data I need.

I'm sure David Fregoli is a solution, but the query package works fine and easy.

Thanks to both of them.

+1
source

I am not familiar with coffeescript, however, one of the default Node libraries called http (most often used to configure the server) can make http requests

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

Source: https://habr.com/ru/post/1479901/


All Articles