Javascript 使用 Node.js 和 Express 进行简单的 API 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8515872/
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
Simple API Calls with Node.js and Express
提问by John
I'm just getting started with Node, APIs, and web applications.
我刚刚开始使用 Node、API 和 Web 应用程序。
I understand the basic workings of Node.js and Express, but now I want to start making calls to other service's APIs and to do stuff with their data.
我了解 Node.js 和 Express 的基本工作原理,但现在我想开始调用其他服务的 API 并处理它们的数据。
Can you outline basic HTTP requests and how to grab/parse the responses in Node? I'm also interested in adding specific headers to my request (initially I'm using the http://www.getharvest.comAPI to crunch my time sheet data).
您能否概述基本的 HTTP 请求以及如何在 Node 中获取/解析响应?我也有兴趣向我的请求添加特定的标题(最初我使用http://www.getharvest.comAPI 来处理我的时间表数据)。
P.S. This seems simple, but a lot of searching didn't turn up anything that answered my question. If this is dupe, let me know and I'll delete.
PS 这看起来很简单,但是很多搜索都没有找到任何可以回答我的问题的东西。如果这是骗人的,请告诉我,我会删除。
Thanks!
谢谢!
回答by alessioalex
You cannot fetch stuff with Express, you should use Mikeal's requestlibrary for that specific purpose.
您无法使用 Express 获取内容,您应该为此特定目的使用 Mikeal 的请求库。
The API for that library is very simple:
该库的 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.
}
})
Edit: You're better of using this library instead of the http default one because it has a much nicer API and some more advanced features (it even supports cookies).
编辑:您最好使用这个库而不是 http 默认库,因为它有更好的 API 和一些更高级的功能(它甚至支持 cookie)。
回答by Nicolas Modrzyk
You can use the http client:
您可以使用 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
});
Also, you can set headers as described in the api documentation:
client.request(method='GET', path, [request_headers])
回答by Ram Pukar
Required install two package.
需要安装两个包。
npm install ejs
npm install request
server.js
服务器.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
索引.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);
}
});
Output
输出