NodeJS HttpGet 到带有 JSON 响应的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20304862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:24:38  来源:igfitidea点击:

NodeJS HttpGet to a URL with JSON response

jsonnode.jsapicurlhttprequest

提问by CaliCoder

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 documentationand this SO post.

我是 Node 开发的新手,我正在尝试使用带有 JSON 响应的 RESTful 协议进行服务器端 API 调用。我已经阅读了API 文档和这篇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

我试图从轨道总线中提取的 API 并在 JSON 输出中返回数据。我对如何使用实际 URL 中的所有参数和选项发出 HTTP GET 请求感到困惑。API 及其响应甚至可以通过浏览器或使用“curl”命令访问。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?

如何编写 Node 服务器端代码以向资源发出 GET 请求,并在 URL 中包含选项并解释 JSON 响应?

Thanks in advance!

提前致谢!

回答by Matt Esch

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

request 模块让这一切变得非常简单。从 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
    }
})

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

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