2011-04-13 84 views
134

Node.js的,比使用子進程,使捲曲通話外,有沒有辦法讓遠程服務器調用CURL REST API並獲得返回的數據?如何在Node.js中進行遠程REST調用?任何CURL?

我還需要設置請求標頭到遠程REST調用,以及GET(或POST)中的查詢字符串。

我覺得這是一個:http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

但它並不顯示任何發佈方式查詢字符串。

+0

我寫了這個https://github.com/jonataswalker/vps-rest-client – 2016-09-28 10:57:29

回答

159

http.request

var options = { 
    host: url, 
    port: 80, 
    path: '/resource?id=foo&bar=baz', 
    method: 'POST' 
}; 

http.request(options, function(res) { 
    console.log('STATUS: ' + res.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res.headers)); 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
    console.log('BODY: ' + chunk); 
    }); 
}).end(); 
+3

所以,即使它是POST,我也在查詢字符串追加數據? – murvinlai 2011-04-13 18:28:47

+3

@murvinlai不確定。去閱讀文檔,來源,HTTP規範。不是該地區的專家。 – Raynos 2011-04-13 19:09:50

+0

版本6.18文檔:http://nodejs.org/docs/v0.6.18/api/http.html#http_http_request_options_callback – weisjohn 2012-06-15 14:58:59

29

http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/

var https = require('https'); 

/** 
* HOW TO Make an HTTP Call - GET 
*/ 
// options for GET 
var optionsget = { 
    host : 'graph.facebook.com', // here only the domain name 
    // (no http/https !) 
    port : 443, 
    path : '/youscada', // the rest of the url with parameters if needed 
    method : 'GET' // do GET 
}; 

console.info('Options prepared:'); 
console.info(optionsget); 
console.info('Do the GET call'); 

// do the GET request 
var reqGet = https.request(optionsget, function(res) { 
    console.log("statusCode: ", res.statusCode); 
    // uncomment it for header details 
// console.log("headers: ", res.headers); 


    res.on('data', function(d) { 
     console.info('GET result:\n'); 
     process.stdout.write(d); 
     console.info('\n\nCall completed'); 
    }); 

}); 

reqGet.end(); 
reqGet.on('error', function(e) { 
    console.error(e); 
}); 

/** 
* HOW TO Make an HTTP Call - POST 
*/ 
// do a POST request 
// create the JSON object 
jsonObject = JSON.stringify({ 
    "message" : "The web of things is approaching, let do some tests to be ready!", 
    "name" : "Test message posted with node.js", 
    "caption" : "Some tests with node.js", 
    "link" : "http://www.youscada.com", 
    "description" : "this is a description", 
    "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png", 
    "actions" : [ { 
     "name" : "youSCADA", 
     "link" : "http://www.youscada.com" 
    } ] 
}); 

// prepare the header 
var postheaders = { 
    'Content-Type' : 'application/json', 
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8') 
}; 

// the post options 
var optionspost = { 
    host : 'graph.facebook.com', 
    port : 443, 
    path : '/youscada/feed?access_token=your_api_key', 
    method : 'POST', 
    headers : postheaders 
}; 

console.info('Options prepared:'); 
console.info(optionspost); 
console.info('Do the POST call'); 

// do the POST call 
var reqPost = https.request(optionspost, function(res) { 
    console.log("statusCode: ", res.statusCode); 
    // uncomment it for header details 
// console.log("headers: ", res.headers); 

    res.on('data', function(d) { 
     console.info('POST result:\n'); 
     process.stdout.write(d); 
     console.info('\n\nPOST completed'); 
    }); 
}); 

// write the json data 
reqPost.write(jsonObject); 
reqPost.end(); 
reqPost.on('error', function(e) { 
    console.error(e); 
}); 

/** 
* Get Message - GET 
*/ 
// options for GET 
var optionsgetmsg = { 
    host : 'graph.facebook.com', // here only the domain name 
    // (no http/https !) 
    port : 443, 
    path : '/youscada/feed?access_token=you_api_key', // the rest of the url with parameters if needed 
    method : 'GET' // do GET 
}; 

console.info('Options prepared:'); 
console.info(optionsgetmsg); 
console.info('Do the GET call'); 

// do the GET request 
var reqGet = https.request(optionsgetmsg, function(res) { 
    console.log("statusCode: ", res.statusCode); 
    // uncomment it for header details 
// console.log("headers: ", res.headers); 


    res.on('data', function(d) { 
     console.info('GET result after POST:\n'); 
     process.stdout.write(d); 
     console.info('\n\nCall completed'); 
    }); 

}); 

reqGet.end(); 
reqGet.on('error', function(e) { 
    console.error(e); 
}); 
+1

我如何訪問d的值? d = {「data」:[{「id」:1111,「name」:「peter」}]}。如何獲得名稱價值? – peter 2013-02-18 12:58:31

+2

設法通過使用var thed = JSON.parse(d)獲取值; \t \t console.log(「the id is:」+ thed.data [0] .id); \t \t 但有些時候,我得到「意外的輸入結束」 – peter 2013-02-19 07:52:44

10

我一直在使用restler製作Web服務調用,就像魅力,是非常整潔。

1

您可以使用curlrequest輕鬆設置你想做的事......你可以在選項甚至套頭爲「」瀏覽器什麼時候打電話的請求。

64

如何使用Request — Simplified HTTP client

這裏有一個GET:

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. 
    } 
}) 

OP也想要一個POST:

request.post('http://service.com/upload', {form:{key:'value'}}) 
+0

在google.com上正常工作,但在請求facebook的圖表api時返回「RequestError:Error:socket掛斷」。請指導,謝謝! – 2017-06-28 16:04:40

+0

這個模塊包含很多問題! – 2017-11-10 14:24:25

+0

如何以這種方式使用REST API傳遞請求參數? – vdenotaris 2018-02-25 11:18:07

3

一個另一個例子 - 你需要安裝請求模塊爲

var request = require('request'); 
function get_trustyou(trust_you_id, callback) { 
    var options = { 
     uri : 'https://api.trustyou.com/hotels/'+trust_you_id+'/seal.json', 
     method : 'GET' 
    }; 
    var res = ''; 
    request(options, function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
      res = body; 
     } 
     else { 
      res = 'Not Found'; 
     } 
     callback(res); 
    }); 
} 

get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){ 
    console.log(resp); 
}); 
3
var http = require('http'); 
var url = process.argv[2]; 

http.get(url, function(response) { 
    var finalData = ""; 

    response.on("data", function (data) { 
    finalData += data.toString(); 
    }); 

    response.on("end", function() { 
    console.log(finalData.length); 
    console.log(finalData.toString()); 
    }); 

}); 
3

我沒有發現任何與捲曲,所以我寫了一個包裝node-libcurl,可以在https://www.npmjs.com/package/vps-rest-client找到。

爲了使POST是像這樣:

var host = 'https://api.budgetvm.com/v2/dns/record'; 
var key = 'some___key'; 
var domain_id = 'some___id'; 

var rest = require('vps-rest-client'); 
var client = rest.createClient(key, { 
    verbose: false 
}); 

var post = { 
    domain: domain_id, 
    record: 'test.example.net', 
    type: 'A', 
    content: '111.111.111.111' 
}; 

client.post(host, post).then(function(resp) { 
    console.info(resp); 

    if (resp.success === true) { 
    // some action 
    } 
    client.close(); 
}).catch((err) => console.info(err)); 
1

如果你有Node.js的4.4+,看看reqclient,它允許你撥打電話和登錄捲曲風格的要求,因此您可以輕鬆地在應用程序外部檢查和再現呼叫。

返回Promise對象,而不是通過簡單的回調,所以你可以在一個更「時尚」方式處理結果,chain結果很容易,並以標準的方式處理錯誤。還爲每個請求刪除了許多樣板配置:基本URL,超時,內容類型格式,默認標題,URL中的參數和查詢綁定以及基本緩存功能。

這是如何初始化,撥打電話並與捲曲風格的登錄操作的例子:

var RequestClient = require("reqclient").RequestClient; 
var client = new RequestClient({ 
    baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true}); 
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"}); 

這將登錄控制檯...

[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json 

並且當響應返回時...

[Response client/orders]<- Status 200 - {"orderId": 1320934} 

This是如何處理與該承諾對象的響應的示例:npm install reqclient

client.get("reports/clients") 
    .then(function(response) { 
    // Do something with the result 
    }).catch(console.error); // In case of error ... 

當然,它可以與被安裝。

18

我使用node-fetch,因爲它使用熟悉的(如果您是網絡開發人員)fetch() API。 fetch()是從瀏覽器發出任意HTTP請求的新方法。

是的我知道這是一個節點js的問題,但我們不是想減少API的開發人員必須記住和理解的數量,並提高我們的JavaScript代碼的可重用性嗎? Fetch is a standard那我們如何匯合呢?

有關獲取其他好處()是返回一個JavaScript Promise,所以你可以寫異步代碼:

let fetch = require('node-fetch'); 

fetch('http://localhost', { 
    method: 'POST', 
    headers: {'Content-Type': 'application/json'}, 
    body: '{}' 
}).then(response => { 
    return response.json(); 
}).catch(err => {console.log(err);}); 

取取代版本XMLHTTPRequest。這裏有一些more info

相關問題