NodeJS HttpGet to a URL with JSON response

谁都会走 提交于 2019-12-18 10:04:15

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/20304862/nodejs-httpget-to-a-url-with-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!