是否有人将API响应的示例从http.request()
发送回第三方并返回给我的clientSever并写入客户端浏览器?
我一直陷入困境,我确信这是一种简单的逻辑。我正在使用快递阅读文档,它似乎没有为此提供抽象。
由于
答案 0 :(得分:13)
请注意,这里的答案有点过时了 - 你会得到一个弃用的警告。 2013年的等价物可能是:
app.get('/log/goal', function(req, res){
var options = {
host : 'www.example.com',
path : '/api/action/param1/value1/param2/value2',
port : 80,
method : 'GET'
}
var request = http.request(options, function(response){
var body = ""
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
res.send(JSON.parse(body));
});
});
request.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
request.end();
});
如果你要编写很多这些模块,我也会推荐request模块。从长远来看,它会为你节省大量的击键!
答案 1 :(得分:8)
以下是在快速获取功能中访问外部API的快速示例:
app.get('/log/goal', function(req, res){
//Setup your client
var client = http.createClient(80, 'http://[put the base url to the api here]');
//Setup the request by passing the parameters in the URL (REST API)
var request = client.request('GET', '/api/action/param1/value1/param2/value2', {"host":"[put base url here again]"});
request.addListener("response", function(response) { //Add listener to watch for the response
var body = "";
response.addListener("data", function(data) { //Add listener for the actual data
body += data; //Append all data coming from api to the body variable
});
response.addListener("end", function() { //When the response ends, do what you will with the data
var response = JSON.parse(body); //In this example, I am parsing a JSON response
});
});
request.end();
res.send(response); //Print the response to the screen
});
希望有所帮助!
答案 2 :(得分:2)
此示例与您尝试实现的内容非常相似(纯Node.js,无快递):
http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html
HTH