NodeJS HttpGet到具有JSON响应的URL

Cal*_*der 57 api json curl httprequest node.js

我是Node开发的新手,我正在尝试使用带有JSON响应的RESTful协议进行服务器端API调用.我已经阅读了API文档和这篇SO帖子.

我试图从跟踪总线中获取的API并在JSON输出中返回数据.我对如何使用实际URL中的所有参数和选项发出HTTP GET请求感到困惑.甚至可以通过浏览器或使用'curl'命令访问API及其响应.http://developer.cumtd.com/api/v2.2/json/GetStop?key=d99803c970a04223998cabd90a741633&stop_id=it

如何编写节点服务器端代码以使用URL中的选项向资源发出GET请求并解释JSON响应?

提前致谢!

Mat*_*sch 124

请求模块使这很容易.从npm将请求安装到您的包中,然后您可以发出get请求.

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
    }
})
Run Code Online (Sandbox Code Playgroud)

您可以在npm找到请求文档:https://npmjs.org/package/request

  • 在我的例子中,将`json`设置为`true`会将解析后的JSON作为正文返回.这些示例显示resp的返回值是一个流,而不是您可以解析的值.结果以任何方式异步返回. (2认同)