栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Node.js连接到REST API

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Node.js连接到REST API

是的,Node.js非常适合于调用外部API。就像Node中的所有内容一样,进行这些调用的功能都是基于事件的,这意味着要做一些事情,例如缓冲响应数据,而不是接收单个完整的响应。

例如:

// get walking directions from central park to the empire state buildingvar http = require("http");    url = "http://maps.googleapis.com/maps/api/directions/json?origin=Central Park&destination=Empire State Building&sensor=false&mode=walking";// get is a simple wrapper for request()// which sets the http method to GETvar request = http.get(url, function (response) {    // data is streamed in chunks from the server    // so we have to handle the "data" event        var buffer = "",         data,        route;    response.on("data", function (chunk) {        buffer += chunk;    });    response.on("end", function (err) {        // finished transferring data        // dump the raw data        console.log(buffer);        console.log("n");        data = JSON.parse(buffer);        route = data.routes[0];        // extract the distance and time        console.log("Walking Distance: " + route.legs[0].distance.text);        console.log("Time: " + route.legs[0].duration.text);    }); });

如果要进行很多此类调用,找到一个简单的包装库(或编写自己的包装库)可能很有意义。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号