Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS HttpGet to a URL with JSON response

I'm new to Node development and I'm trying to make a server-side API call using a RESTful protocol with a JSON response. I've read up on both the API documentation and this SO post.

The API that I'm trying to pull from tracks busses and returns data in a JSON output. I'm confused on how to make a HTTP GET request with all parameters and options in the actual URL. The API and it's response can even be accessed through a browser or using the 'curl' command. http://developer.cumtd.com/api/v2.2/json/GetStop?key=d99803c970a04223998cabd90a741633&stop_id=it

How do I write Node server-side code to make GET requests to a resource with options in the URL and interpret the JSON response?

Thanks in advance!

like image 500
CaliCoder Avatar asked Nov 30 '13 19:11

CaliCoder


People also ask

How do I parse JSON response in node JS?

nodejs-parse-json-file.js // include file system module var fs = require('fs'); // read file sample. json file fs. readFile('sample. json', // callback function that is called when reading file is done function(err, data) { // json data var jsonData = data; // parse json var jsonParsed = JSON.

How can I get JSON data from URL?

Get JSON From URL Using jQuerygetJSON(url, data, success) is the signature method for getting JSON from an URL. In this case, the URL is a string that ensures the exact location of data, and data is just an object sent to the server. And if the request gets succeeded, the status comes through the success .


1 Answers

request is now deprecated. It is recommended you use an alternative:

  • native HTTP/S, const https = require('https');
  • node-fetch
  • axios
  • got
  • superagent

Stats comparision Some code examples

Original answer:

The request module makes this really easy. Install request into your package from npm, and then you can make a get request.

var request = require("request")  var url = "http://developer.cumtd.com/api/v2.2/json/GetStop?" +     "key=d99803c970a04223998cabd90a741633" +     "&stop_id=it"  request({     url: url,     json: true }, function (error, response, body) {      if (!error && response.statusCode === 200) {         console.log(body) // Print the json response     } }) 

You can find documentation for request on npm: https://npmjs.org/package/request

like image 95
Matt Esch Avatar answered Oct 09 '22 02:10

Matt Esch