nodejs使用request傳送http請求
在nodejs的開發中,有時需要後臺去呼叫其他伺服器的介面,這個時候,就需要傳送HTTP請求了。有一個簡單的工具可以用, Simplified HTTP request client,可以比較方便的模擬請求
安裝
npm install --save request
使用
最簡單的GET請求,用法如下:
var request = require('request'); request('(error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Show the HTML for the baidu homepage. } })
POST application/json
request({ url: url, method: "POST", json: true, headers: { "content-type": "application/json", }, body: JSON.stringify(requestData) }, function(error, response, body) { if (!error && response.statusCode == 200) { } });
POST application/x-www-form-urlencoded
request.post({url:'{key:'value'}}, function(error, response, body) { if (!error && response.statusCode == 200) { } })
POST multipart/form-data
var formData = { // Pass a simple key-value pair my_field: 'my_value', // Pass data via Buffers my_buffer: new Buffer([1, 2, 3]), // Pass data via Streams my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), }; request.post({url:'}, function (error, response, body) { if (!error && response.statusCode == 200) { } })
如上所示,formData可以直接放key-value格式的資料,也可以放buffer,或者是透過流描述的檔案。
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69901823/viewspace-2942022/,如需轉載,請註明出處,否則將追究法律責任。