使用Node.js和Express进行简单的API调用

问题描述 投票:43回答:3

我刚刚开始使用Node,API和Web应用程序。

我理解Node.js和Express的基本工作方式,但现在我想开始调用其他服务的API并对它们的数据进行处理。

您能概述一下基本的HTTP请求以及如何在Node中获取/解析响应吗?我也有兴趣在我的请求中添加特定的标题(最初我使用http://www.getharvest.com API来处理我的时间表数据)。

附:这看起来很简单,但很多搜索没有找到任何回答我问题的东西。如果这是欺骗,请告诉我,我会删除。

谢谢!

javascript node.js ajax api express
3个回答
48
投票

你不能用Express获取东西,你应该使用Mikeal的request库来实现这个目的。

该库的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和一些更高级的功能(它甚至支持cookie)。


5
投票

您可以使用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 documentation中的说明设置标题:

client.request(method='GET', path, [request_headers])

3
投票

需要安装两个包。

npm install ejs 
npm 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);
    }
});

产量

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.