Joh*_*ohn 48 javascript api ajax node.js express
我刚刚开始使用Node,API和Web应用程序.
我理解Node.js和Express的基本工作方式,但现在我想开始调用其他服务的API并对它们的数据进行处理.
您能概述一下基本的HTTP请求以及如何在Node中获取/解析响应吗?我也有兴趣在我的请求中添加特定的标题(最初我使用http://www.getharvest.com API来处理我的时间表数据).
PS这看起来很简单,但很多搜索没有找到任何回答我问题的东西.如果这是欺骗,请告诉我,我会删除.
谢谢!
ale*_*lex 52
您无法使用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.
}
})
Run Code Online (Sandbox Code Playgroud)
编辑:你最好使用这个库而不是http默认库,因为它有一个更好的API和一些更高级的功能(它甚至支持cookie).
您可以使用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
});
Run Code Online (Sandbox Code Playgroud)
client.request(method='GET', path, [request_headers])
Run Code Online (Sandbox Code Playgroud)
小智 5
需要安装两个包。
npm install ejs
npm install request
Run Code Online (Sandbox Code Playgroud)
服务器.js
var request = require('request');
app.get('/users', function(req, res) {
request('https://jsonplaceholder.typicode.com/users', function(error, response, body) {
res.json(body)
});
});
Run Code Online (Sandbox Code Playgroud)
索引.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);
}
});
Run Code Online (Sandbox Code Playgroud)
输出
归档时间: |
|
查看次数: |
62881 次 |
最近记录: |