使用Node.js和Express进行简单的API调用
我刚刚开始使用Node,API和Web应用程序。
我理解Node.js和Express的基本工作原理,但是现在我想开始调用其他服务的API并使用它们的数据来完成任务。
你能概述基本的HTTP请求,以及如何抓取/parsingNode中的响应吗? 我也有兴趣在我的请求中添加特定的头文件(最初我使用http://www.getharvest.com API来压缩我的时间表数据)。
PS这看起来很简单,但是很多search没有find任何回答我的问题的东西。 如果这是愚蠢的,让我知道,我会删除。
谢谢!
你不能用Express取东西,你应该使用Mikeal的请求库来达到这个目的。
该库的API非常简单:
var request = require('request'); request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Print the google web page. } })
编辑:你最好使用这个库,而不是http默认的,因为它有一个更好的API和一些更高级的function(它甚至支持cookies)。
你可以使用http客户端:
var http = require('http'); var client = http.createClient(3000, 'localhost'); var request = client.request('PUT', '/users/1'); request.write("stuff"); request.end(); request.on("response", function (response) { // handle the response });
另外,您可以按照api文档中所述设置标题:
client.request(method='GET', path, [request_headers])
需要安装两个包。
npm install ejs nmp install request
server.js
var request = require('request'); app.get('/users', function(req, res) { request('https://jsonplaceholder.typicode.com/users', function(error, response, body) { res.json(body) }); });
index.ejs
$.ajax({ type: "GET", url: 'http://127.0.0.1:3000/posts', dataType: "json", success: function(res) { var res_data = JSON.parse(res); console.log(res_data); } });
产量